2013-06-30 29 views
1

我创建了一个数组列表。但我试图访问特定的索引来拉特定的数组,所以我可以循环。并从中获取价值。我甚至不知道如何启动代码。我的数组列表中的每个项目都带有1个带有5个值的aray。有什么建议么?C#从包含数组的列表中循环索引

+1

这将有助于了解你所使用的语言! –

+0

哪种语言? – dejavu

+4

您应该发布现有代码的片段。 –

回答

2

如何像这样

List<int[]> l = new List<int[]>(); 
l.Add(new int[] { 1, 2, 3 }); 
l.Add(new int[] { 2, 3, 4 }); 
l.Add(new int[] { 3, 4, 5 }); 
int a = l[2][2]; // a = 5 
+0

这显示了OP如何访问列表中给定数组的给定元素,而不是如何循环访问列表中的给定数组,这正是他们所要求的。 – Tim

1

您可以通过特定的阵列使用在列表中循环索引,如果你知道它的索引。

例如,假设你有一个名为listOfArrays列表,你通过第二阵列要循环:

foreach (int element in listOfArrays[1]) 
{ 
    // do something with the array 
} 

listOfArrays[1]将返回INT []在列表中的第二位置。

或者,你可以遍历整个列表处理每个阵列像这样:

foreach (int[] arr in listOfArrays) 
{ 

    foreach (int element in arr) 
    { 

     // do something with the array 
    } 
} 

但它听起来就像你正在寻找只需在列表中访问指定的数组,不是所有的人。

0

希望,一些例子帮助你

List<int[]> myList = new List<int[]>(); // <- MyList is list of arrays of int 

// Let's add some values into MyList; pay attention, that arrays are not necessaily same sized arrays: 

myList.Add(new int[] {1, 2, 3}); 
myList.Add(new int[] {4, 5, 6, 7, 8}); 
myList.Add(new int[] {}); // <- We can add an empty array if we want 
myList.Add(new int[] {100, 200, 300, 400}); 

// looping through MyList and arrays 

int[] line = myList[1]; // <- {4, 5, 6, 7, 8} 
int result = line[2]; // <- 6 

// let's sum the line array's items: 4 + 5 + 6 + 7 + 8 

int sum = 0; 

for (int i = 0; i < line.Length; ++i) 
    sum += line[i]; 

// another possibility is foreach loop: 
sum = 0; 

foreach(int value in line) 
    sum += value; 

// let's sum up all the arrays within MyList 
totalSum = 0; 

for (int i = 0; i < myList.Count; ++i) { 
    int[] myArray = myList[i]; 

    for (int j = 0; j < myArray.Length; ++j) 
    totalSum += myArray[j]; 
} 

// the same with foreach loop 
totalSum = 0; 

foreach(int[] arr in myList) 
    foreach(int value in arr) 
    totalSum += value;