我创建了一个数组列表。但我试图访问特定的索引来拉特定的数组,所以我可以循环。并从中获取价值。我甚至不知道如何启动代码。我的数组列表中的每个项目都带有1个带有5个值的aray。有什么建议么?C#从包含数组的列表中循环索引
1
A
回答
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;
相关问题
- 1. 每个循环的数组索引C#
- 2. 用包含数组的另一个列表索引列表
- 3. Python中列表的循环索引
- 4. 查找循环中列表的索引
- 5. for循环中的Python数组索引
- 6. for循环中的数组索引
- 7. Django计数器循环索引列表
- 8. 循环数组列表中
- 9. 数组索引循环变量在C中重置为零,C++
- 10. 包含的nunjucks文件中的循环索引
- 11. C++/Cli循环包含
- 12. 从数组中的Foreach循环以及如何包含它
- 13. 如何循环在C中没有索引的数组?
- 14. 索引超出了for循环中数组的范围C#
- 15. 嵌套列表中的Python嵌套列表不包含循环
- 16. 跳过/忽略包含c中值的数组索引
- 17. 循环访问数组的索引
- 18. Python的数组索引for循环
- 19. C头文件中的包含循环
- 20. c#在for循环中从数组索引中减去一个数字
- 21. 访问.net表达式循环中的数组索引
- 22. 当索引不包含在另一个列表中时,从索引中删除
- 23. IndexError:列表索引超出范围列表中的for循环
- 24. Python for循环:索引列表中的一个项目列表
- 25. 列表,data.frame循环和索引问题
- 26. 列表索引while循环python
- 27. Struts 2对象循环列表索引
- 28. Thymeleaf - 如何循环索引列表
- 29. PHP - 通过索引JSON数组循环
- 30. 嫩枝循环数组索引
这将有助于了解你所使用的语言! –
哪种语言? – dejavu
您应该发布现有代码的片段。 –