如何在C#.Net泛型集合中按索引处理嵌套列表的元素?

如何在C#.Net泛型集合中按索引处理嵌套列表的元素?,c#,list,generics,C#,List,Generics,这看起来很简单,但是如何通过索引处理嵌套列表的元素呢 我最近与一位同事共享了一个C#类,该类返回了一个列表,而他的同事不知道如何处理生成的列表集合,并且在StackOverflow上找不到它。描述如何为列表编制索引,但不描述如何处理嵌套列表。使用索引器从父列表获取子列表,然后使用另一个索引器获取列表中的实际项。也可以使用或其他,和或其他 //为演示创建锯齿状数组 List NestedListofList=(新列表[]){ (新的int[]{1,2,3}).ToList(), (新的int[]{

这看起来很简单,但是如何通过索引处理嵌套列表的元素呢


我最近与一位同事共享了一个C#类,该类返回了一个
列表
,而他的同事不知道如何处理生成的
列表
集合,并且在StackOverflow上找不到它。描述如何为
列表编制索引,但不描述如何处理嵌套列表。

使用索引器从父列表获取子列表,然后使用另一个索引器获取列表中的实际项。也可以使用或其他,和或其他

//为演示创建锯齿状数组
List NestedListofList=(新列表[]){
(新的int[]{1,2,3}).ToList(),
(新的int[]{4,5}).ToList(),
(新int[]{6}).ToList()
}).ToList();
//一种处理列表列表的方法返回3:5:6
Console.WriteLine(“{0}:{1}:{2}”,
NestedListOfLists[0][2],//NestedListOfLists[0]返回第一个列表,然后可以使用[2]为第三个元素编制索引
NestedListOfLists[1][1],//NestedListOfLists[1]返回第一个列表,然后用[1]索引该列表
NestedListOfLists[2][0]//NestedListOfLists[2]返回第一个列表,然后用[0]索引该列表
);
/*Console.WriteLine({0}),
NestedListOfLists[1,0]//这不会编译
);*/
//处理列表列表的另一种方法
Console.WriteLine({0}),
(NestedListOfLists.ElementAt(0)).ElementAt(2)//NestedListOfLists.ElementAt(0)返回第一个列表,然后可以使用ElementAt(2)为第三个元素编制索引
);
//有时遍历列表是很实际的
foreach(嵌套列表中的列表IntList)
{
Write(“列表{0}:\t”,IntList.Count());
foreach(IntList中的inti)
{
写入(“{0}\t”,i);
}
控制台。写入(“\n”);
}

你的意思是,如果你有一个类型为
列表的变量,你如何访问它的元素?@ChrisSinclair他问了这个问题,并在几秒钟内回答了这个问题。@deathismyfriend:啊,是的,呜呜。我没注意到。谢谢
    // 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");
    }