[英]How to create a List variable that can contain array of int or string in C#?
[英]How to create an array of List<int> in C#?
我有一個需要arrayList數組的問題。
例如,如果我們使用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);
我們如何在C#中實現像上面這樣的數據結構?
在C語言中,它就像一個LinkedList數組。 如何在C#中執行相同的操作?
var myData = new List<int>[]
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 }
};
幾乎按照您的嘗試,只有第一行是錯誤的:
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#中的泛型列表的一些信息: 單擊我
另外,如果您想閱讀一些有關數組的內容,例如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);
我更喜歡清單,但取決於您...
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();
您正在嘗試采用具體類型List<int>
並對其進行排列。
就像string
變成new string[2]
, List<int>
變成new List<int>[2]
。
這將創建一個可以容納兩個List<int>
的數組。
但是,數組中的每個元素都以null
開頭。
您需要在使用數組之前將new List<int>()
放入數組的每個插槽中。
但是,您可能應該使用List<List<int>>
而不是列表數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.