【问题标题】:C# Loop through an index from a list which holds an arrayC#循环遍历包含数组的列表中的索引
【发布时间】:2013-06-30 08:00:07
【问题描述】:

我创建了一个数组列表。但我试图访问一个特定的索引来拉出特定的数组,这样我就可以循环遍历。并从中获取价值。我什至不知道如何启动代码。我的数组列表中的每个项目都有 1 个数组和 5 个值。有什么建议吗?

【问题讨论】:

  • 了解您使用的语言会有所帮助!
  • 您应该发布现有代码的 sn-p。

标签: c# arrays list loops


【解决方案1】:

这样的事情怎么样

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

【讨论】:

  • 这显示了 OP 如何访问列表中给定数组的给定元素,而不是如何遍历列表中的给定数组,这似乎是他们要问的。跨度>
【解决方案2】:

如果你知道它的索引,你可以使用 List 中的索引来循环遍历一个特定的数组。

例如,假设您有一个名为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
    }
}

但听起来您只是想访问列表中的指定数组,而不是全部。

【讨论】:

    【解决方案3】:

    希望,一些例子可以帮助你

    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; 
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多