如何在C#.Net泛型集合中按索引解决嵌套列表的元素? [英] How do I address the elements of a nested List-of-Lists by index in C#.Net generic collections?
问题描述
这似乎很简单,但是如何通过索引处理嵌套列表的元素呢?
This seems like a simple thing, but how do I address the elements of a nested List-of-Lists by index?
我最近与一个不知道如何解决所得的 List< List< List< List<< List<< List<<<<<<<<<<<<<<<><<<<<><<<<< List<<<<<<<<<><<<<<<<<<<<<<<<<<><<<<<><<<< List<<<<<>>>">;
集合,但在StackOverflow上找不到它.在列表中查找整数的索引描述了如何建立索引 List< int>
,而不是如何处理嵌套列表.
I recently shared a C# class that returned a List<List<int>>
with a colleague who didn't know how to address the resulting List<List<int>>
collection and couldn't find it on StackOverflow. find index of an int in a list describes how to index a List<int>
, but not how to address nested lists.
推荐答案
使用索引器从父列表中获取子列表,然后使用另一个索引器来获取列表中的实际项目.也可以使用 ElementAt
或其他列表函数和迭代器.
Use an indexer to get the child list from the parent list, then use another indexer to get the actual item in the list. One may also use ElementAt
or other list functions, and foreach
or other iterators.
// create a jagged array for demo
List<List<int>> NestedListOfLists = (new List<int>[] {
(new int[] { 1, 2, 3 }).ToList(),
(new int[] { 4, 5 }).ToList(),
(new int[] { 6 }).ToList()
}).ToList();
// one way to address a List of Lists, returns 3:5:6
Console.WriteLine("{0}:{1}:{2}",
NestedListOfLists[0][2], // NestedListOfLists[0] returns the first list, which then can be indexed with [2] for the third element
NestedListOfLists[1][1], // NestedListOfLists[1] returns the first list, which is then indexed with [1]
NestedListOfLists[2][0] // NestedListOfLists[2] returns the first list, which is then indexed with [0]
);
/*Console.WriteLine("{0}",
NestedListOfLists[1,0] // this doesn't compile
);*/
// another way to address a List of Lists
Console.WriteLine("{0}",
(NestedListOfLists.ElementAt(0)).ElementAt(2) // NestedListOfLists.ElementAt(0) returns the first list, which then can be indexed with ElementAt(2) for the third element
);
// sometimes its practical to iterate through the lists
foreach( List<int> IntList in NestedListOfLists)
{
Console.Write("List of {0}: \t", IntList.Count() );
foreach (int i in IntList)
{
Console.Write("{0}\t", i );
}
Console.Write("\n");
}
这篇关于如何在C#.Net泛型集合中按索引解决嵌套列表的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!