【问题标题】:C# adding elements to list in the list (two dimensional list)C#在列表中添加元素到列表(二维列表)
【发布时间】:2016-01-03 18:48:14
【问题描述】:

我有一个清单:

List <List <string>> aList = new List <List <string>> ();

我想在此列表中的列表中添加一些内容,如下所示:

aList [0].Add ("item");

但我得到ArgumentOutOfRangeException,为什么?

将列表添加到列表中效果很好:

List <string> testList = new List <string> ();
testList.Add ("item");
aList.Add (testList);

没有任何错误。 我做错了什么?

【问题讨论】:

  • 因为列表一开始是空的,所以aList[0](获取第一项)是不可能的。

标签: c# list exception generics dimensional


【解决方案1】:

添加索引的第一条语句假定列表的大小>=1,但事实并非如此。只是初始化不会创建一个大小的列表。

【讨论】:

    【解决方案2】:

    好的,我找到了解决我自己问题的方法! 我必须先将任何列表添加到我自己的列表中,因为它是空的,所以我无法访问不存在的列表。

    List <string> testList = new List <string> ();
    aList.Add (testList);
    aList [0].Add ("item");
    

    没有任何错误。

    【讨论】:

      【解决方案3】:
      aList [0].Add ("value");
      

      这失败了,因为位置 0 没有列表可以添加您的值。

      试试

      aList [0] = new List<string>;
      aList [0].Add ("value");
      

      【讨论】:

        【解决方案4】:
        public class Row
        {
            public  List<string> Elements { get; private set; }
        
            public Row()
            {
                Elements = new List<string>();
            }
        
            public Row(List<string> elements)
            {
                Elements = elements;
            }
        }
        

        使用:

        List<Row> rows = new List<Row>();
                rows.Add(new Row( new List<string>(){"abc","abc","abc"}));
                rows.Add(new Row(new List<string>() { "xyz", "xyz", "xyz" }));
        

         Row row = new Row();
                row.Elements.Add("abc");
                row.Elements.Add("xyz");
        
               rows.Add(row);
        

        您不能将元素添加到未声明的列表中

        【讨论】:

          猜你喜欢
          • 2021-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-15
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2021-10-06
          相关资源
          最近更新 更多