列表列表的数组

本文关键字:列表 数组 | 更新日期: 2023-09-27 18:37:26

我正在尝试制作一个列表列表数组,整个事情让我感到困惑。我希望数组是更大的东西,所以我做了List<List<int>>[] arr = new List<List<int>>[5],但是在我添加了一些项目后,我需要通过arr.ElementAt(1).ElementAt(1)[1]访问它们,但不应该反过来([1]在开始时)?

我所要做的就是填充整个三个维度,但是当我尝试通过arr[1].ElementAt(1).Add(...)arr.ElementAt(1)[1].Add(...)添加最后一个维度时(不确定要使用哪个维度,两者都不起作用)我得到一个 arror 说我正在尝试向空列表添加一个值

列表列表的数组

您需要

在使用List<List<int>>之前实例化它们

arr[0] = new List<List<int>>();
arr[0].Add(new List<int>());
arr[0][0].Add(5);
///etc...

另一个注意事项:您看到我如何在List上使用[]括号吗? 这是支持的。

new List<List<int>>[5]

实际上是一个 List of List of int 的数组,但你仍然可以在它上面调用 ElementAt(),因为数组实现了 IEnumerable。

下面显示了与所需数据结构的不同交互,以添加和验证元素。

var arr = new List<List<int>>[]
    {
        new List<List<int>>()
        {
            new List<int>() { 1, 3, 5 },
            new List<int>() { 2, 4, 6 },
        },
        new List<List<int>>() { new List<int>() },
        new List<List<int>>() { new List<int>() },
        new List<List<int>>() { new List<int>() },
        new List<List<int>>() { new List<int>() },
    };
Assert.AreEqual(4, arr[0].ElementAt(1).ElementAt(1));
Assert.AreEqual(3, arr[0].ElementAt(1).Count);
arr[0].ElementAt(1).Add(8);
Assert.AreEqual(4, arr[0].ElementAt(1).Count);
Assert.AreEqual(8, arr[0].ElementAt(1).ElementAt(3));