【问题标题】:Initialize an array of lists of a list with c#用c#初始化列表的列表数组
【发布时间】:2018-10-24 19:46:56
【问题描述】:

我正在尝试初始化声明为 a 的列表的列表数组

List <List<int>>[] a

这里的问题是我不知道语法(我什至不知道上面的语法是否正确)。 我认为它是正确的,因为要初始化声明为 b 的列表数组,使用以下语法:

List<int>[] b = 
{
    new List<int> { 1, 3, 4 }, 
    new List<int> { 3, 4, 12 }
};

谁能帮帮我?

【问题讨论】:

  • 您确定需要int 列表列表的数组吗?看起来很复杂...
  • 是的,这是我必须做的练习

标签: c# arrays list syntax


【解决方案1】:

你有一个 int 列表列表数组:

List<List<int>>[] a = new List<List<int>>[]
{
    new List<List<int>>()
    {
        new List<int>(){1,2,3,4,5},
        new List<int>(){10,20,30,40,50}
    },
    new List<List<int>>()
    {
        new List<int>(){6,7,8,9},
        new List<int>(){60,70,80,90}
    }
};

【讨论】:

  • 这就是我要找的!谢谢。
  • 啊,忍者!您应该为每个List&lt;List&lt;int&gt;&gt; 添加第二个项目。我撤回了我的答案。
  • @D.Dave 如果您将此答案视为答案,请将其标记为。
【解决方案2】:

List 是一个动态数组,尽量坚持一个或另一个。

List&lt;int[]&gt; a = new List&lt;int[]&gt;();是一个int数组列表,可以接受

但你可以只拥有List&lt;int&gt; intlist = new List&lt;int&gt;();

你也可以List&lt;List&lt;int&gt;&gt; listoflistsofints = new List&lt;List&lt;int&gt;&gt;()

然后listoflistsofints.Add(intlist);

一切都完全可行。使用列表而不是数组的原因是大小是动态的,您可以使用.Sort() 方法对列表重新排序,并且添加和替换元素很容易:

intlist.Add(153);

我希望这能为您解决问题,如果您需要了解更多信息,请告诉我!

【讨论】:

  • 感谢您的回答!是的,我会用另一种方式来做,但这是我必须做的练习,你把它清理干净了!
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 2023-03-13
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2015-02-07
相关资源
最近更新 更多