简体   繁体   English

如何创建列表数组 <int> 在C#中?

[英]How to create an array of List<int> in C#?

I have a problem where I need an array of arrayList. 我有一个需要arrayList数组的问题。

For example if we take an Array of ArrayList of int, it will be like: 例如,如果我们使用int的ArrayList的Array,它将类似于:

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);

How can we implement a datastructure like the above in C#? 我们如何在C#中实现像上面这样的数据结构?

In C, its like a array of LinkedList. 在C语言中,它就像一个LinkedList数组。 How can I do the same in C#? 如何在C#中执行相同的操作?

var myData = new List<int>[]
{
    new List<int> { 1, 2, 3 },
    new List<int> { 4, 5, 6 }
};

Almost as you tried, only the first line is incorrect: 几乎按照您的尝试,只有第一行是错误的:

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);

Thanks to madmik3, here is a link you can read something about generic lists in C#: click me 感谢madmik3,这里是一个链接,您可以阅读有关C#中的泛型列表的一些信息: 单击我

Also, if you want to read something about arrays, eg the static copy method of the Array class, here is some link for that. 另外,如果您想阅读一些有关数组的内容,例如Array类的静态复制方法,那么这里有一些链接。

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);

I prefer lists but it's up to you... 我更喜欢清单,但取决于您...

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);

Then if you really want a list at the end of it all use some linq. 然后,如果您真的想要列表的末尾,请全部使用linq。

lst.ToArray();

You're trying to take the concrete type List<int> and make an array of it. 您正在尝试采用具体类型List<int>并对其进行排列。
Just like string becomes new string[2] , so to List<int> becomes new List<int>[2] . 就像string变成new string[2]List<int>变成new List<int>[2]

This will create an array which can hold two List<int> s. 这将创建一个可以容纳两个List<int>的数组。
However, each element in the array starts out null . 但是,数组中的每个元素都以null开头。
You'll need to put a new List<int>() into each slot of the array before using it. 您需要在使用数组之前将new List<int>()放入数组的每个插槽中。


However, you should probably use a List<List<int>> instead of an array of lists. 但是,您可能应该使用List<List<int>>而不是列表数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM