【问题标题】:Getting split Items by Index from an IEnumerable list to add on certain ListView ColumnHeaders?从 IEnumerable 列表中按索引获取拆分项目以添加到某些 ListView ColumnHeaders?
【发布时间】:2016-09-22 15:43:56
【问题描述】:

我有一个名为 Students 的 iEnumerable 列表,它从一个文本文件中读取,该文件由 linq 查询使用 : 分隔符分割。我使用的是 for 循环,而不是 foreach 循环,因为我想将 List by Index 添加到 ListView SubItems。我将如何从 iEnumerable 列表中获取特定的拆分项?

            var Students = File.ReadLines("C:\Folder\student_list.txt")
                .Select(line => line.Split(':'));

            // John:Smith
            // Adam:Turner
            // Abraham:Richards

            for (int i = 0; i < Students.Count(); i++)
            {
                // Listview already has 3 items, I want to add First and Last name of each
                // Item in Students List into ColumnHeader [1] and [2].

                // Before when using a foreach loop and no existing Listview Items, I was doing
                // foreach (var piece in Students)
                //     lvStudents.Items.Add(new ListViewItem(new String[] { piece[0], piece[1] }))

                // How would I do the same up above, but for each SubItem using a for loop?      
            }

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您无法通过索引访问IENumberable。你必须使用

    string[] StudentItems = Students.ElementAt(i);
    

    另一种选择是将for 循环替换为foreach

    foreach (string[] StudentItems in Students)
    

    如果您想通过[] 访问您的项目并避免使用foreach,则必须使用ToList()ToArray()

    string[][] Students = File.ReadLines(@"C:\Folder\student_list.txt")
                              .Select(line => line.Split(':'))
                              .ToArray();
    
    for (int i = 0; i < Students.Count(); i++)
    {
          string[] StudentItems = Students[i];
    

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多