【问题标题】:How to create an array of List<int> in C#?如何在 C# 中创建 List<int> 数组?
【发布时间】:2011-06-19 08:54:09
【问题描述】:

我有一个需要 arrayList 数组的问题。

例如,如果我们取一个 ArrayList 的 int 数组,它将是这样的:

int[]<List> myData = new int[2]<List>;

myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);


myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);

myData[0].Add(7);

我们如何在 C# 中实现上述数据结构?

在 C 语言中,它就像一个 LinkedList 数组。如何在 C# 中做同样的事情?

【问题讨论】:

  • 示例不是ArrayList的数组。
  • int[]&lt;List&gt; 在语法上毫无意义。也许你想要List&lt;int&gt;[]
  • 对于你下一个关于 C# 的问题,我建议用 C# 标记它,否则人们可能找不到它。
  • 我知道 C# 不支持该语法,因此问题是 - 如何以不同的方式进行操作。感谢 C# 标签推荐。我一定会记得的。

标签: c# .net arrays list


【解决方案1】:
var myData = new List<int>[]
{
    new List<int> { 1, 2, 3 },
    new List<int> { 4, 5, 6 }
};

【讨论】:

  • 感谢 Qrystal,这是我需要的解决方案。
  • 你不需要 "List" -- var myData = new[] { new List { 1, 2, 3 }, new List { 4, 5 , 6 } };
【解决方案2】:

几乎和你一样,只有第一行不正确:

List<int>[] myData = new List<int>[2];
myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);


myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);

myData[0].Add(7);

感谢 madmik3,这里有一个链接,您可以在 C# 中阅读有关通用列表的内容: click me

此外,如果您想阅读有关数组的内容,例如Array 类的静态复制方法,here 是其中的一些链接。

【讨论】:

  • 这个答案是对的,但提问者也应该花一点时间来获得更多关于 C# 中的集合和泛型的信息。您将一直使用它们,因此学习它们将有很大帮助。你可以从上面的列表开始:msdn.microsoft.com/en-us/library/6sh2ey19.aspx
【解决方案3】:
var arraySize = 2;
var myArray = new List<Int32>[arraySize];


myArray[0] = new List<Int32>();
myArray[1] = new List<Int32>();
// And so on....

myArray[0].Add(5);

【讨论】:

  • 谢谢克里斯,这是我需要的解决方案。
【解决方案4】:

我更喜欢列表,但这取决于你...

List<List<int>> lst = new List<List<int>>();

lst.Add(new List<int>());
lst.Add(new List<int>());

lst[0].Add(1);
lst[1].Add(1);
lst[1].Add(2);
lst[0].Add(5);

如果你真的想在它的末尾列出一个列表,请使用一些 linq。

lst.ToArray();

【讨论】:

  • C# 区分大小写,List&lt;T&gt; 方法(就像 BCL 中的所有内容一样)是 PascalCased。
  • 呸,复制粘贴错字。感谢您修复它
【解决方案5】:

您正在尝试采用具体类型 List&lt;int&gt; 并为其创建一个数组。
就像string 变成new string[2],所以List&lt;int&gt; 变成new List&lt;int&gt;[2]

这将创建一个可以容纳两个List&lt;int&gt;s 的数组。
但是,数组中的每个元素都以 null 开头。
在使用它之前,您需要将new List&lt;int&gt;() 放入数组的每个插槽中。


但是,您可能应该使用List&lt;List&lt;int&gt;&gt; 而不是列表数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多