linq 是否从IEnumerable列表中获取按索引拆分的项以添加到某些ListView ColumnHeaders?

kd3sttzy  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(115)

我有一个名为Students的iEnumerable列表,它是从一个文本文件中读取的,该文本文件是由一个linq查询使用以下方法拆分的:分隔符。我使用了for循环,而不是foreach循环,因为我想将List by Index添加到ListView子项中。如何从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?      
            }
wlp8pajw

wlp8pajw1#

不能按索引访问IEnumerable。必须使用

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];
}

相关问题