通过索引从IEnumerable列表中获取拆分项以添加到某些ListView ColumnHeaders上?

时间:2016-09-22 07:34:49

标签: c# linq

我有一个名为Students的iEnumerable列表从一个文本文件中读取,该文件由一个linq查询使用:delimiter分割。我正在使用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?      
            }

1 个答案:

答案 0 :(得分: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];