【问题标题】:How do I address the elements of a nested List-of-Lists by index in C#.Net generic collections?如何在 C#.Net 泛型集合中按索引处理嵌套列表的元素?
【发布时间】:2015-11-21 01:25:35
【问题描述】:

这似乎是一件简单的事情,但是如何按索引寻址嵌套列表的元素呢?

我最近与一位同事共享了一个返回 List<List<int>> 的 C# 类,该同事不知道如何处理生成的 List<List<int>> 集合,并且无法在 StackOverflow 上找到它。 find index of an int in a list 描述了如何索引List<int>,但没有描述如何寻址嵌套列表。

【问题讨论】:

  • 你的意思是如果你有一个List<List<object>>类型的变量,你如何访问它的元素?
  • @ChrisSinclair 隔着几秒,他问和回答了这个问题。
  • @deathismyfriend:啊,是的,哎呀。没注意到。谢谢。

标签: c# list generics


【解决方案1】:

使用索引器从父列表中获取子列表,然后使用另一个索引器获取列表中的实际项目。也可以使用ElementAt 或其他list functions,以及foreach 或其他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");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2013-01-17
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2022-07-05
    • 2014-08-25
    • 1970-01-01
    相关资源
    最近更新 更多