C# 创建一个数组数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/549399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:46:30  来源:igfitidea点击:

C# Creating an array of arrays

c#arrays

提问by Fidsah

I'm trying to create an array of arrays that will be using repeated data, something like below:

我正在尝试创建一个将使用重复数据的数组数组,如下所示:

int[] list1 = new int[4] { 1, 2, 3, 4 };
int[] list2 = new int[4] { 5, 6, 7, 8 };
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4, 4] {  list1 ,  list2 ,  list3 ,  list4  };

I can't get it to work and so I'm wondering if I'm approaching this wrong.

我无法让它工作,所以我想知道我是否在接近这个错误。

What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,

我试图做的是创建某种方法来创建一长串值,以便我可以按特定顺序重复处理它们。就像是,

int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};

for (int i = 0; i < 90; ++i) {
   doStuff(lists[i]);
}

and have the arrays passed to doStuff()in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays?

并将数组doStuff()按顺序传递给。我是否完全错误地解决了这个问题,或者我是否缺少创建数组数组的内容?

采纳答案by Sean

What you need to do is this:

你需要做的是:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]>type:

另一种选择是创建一个List<int[]>类型:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

回答by Suroot

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

问题是您试图将列表中的元素定义为多个列表(而不是定义的多个整数)。您应该像这样定义列表。

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

你也可以这样做

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

回答by Noldorin

I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.

我认为您可能正在寻找Jagged Arrays,它与 C# 中的多维数组(如您在示例中使用的)不同。将声明中的数组转换为锯齿状数组应该可以使其工作。但是,您仍然需要使用两个循环来遍历 2D 锯齿状数组中的所有项目。