【问题标题】:List with array [closed]带有数组的列表[关闭]
【发布时间】:2013-02-03 20:29:21
【问题描述】:

我有这样的结构

List<int[]> nodeIds = new List<int[]>();

我可以从int[] 获取每个元素吗?我该怎么做?

【问题讨论】:

  • 在问这些问题之前先了解一些编程基础知识

标签: c# arrays list


【解决方案1】:

您有一个Listint[],因此您需要做的是获取List 中每个项目的每个元素。为此,您必须使用嵌套循环 - 一个在列表上,第二个在当前考虑的列表项的数组上。

【讨论】:

    【解决方案2】:

    您可以使用 Linq Enumerable.SelectMany 方法将序列展平为一个序列:

    IEnumerable<int> allIds = nodeIds.SelectMany(x => x);
    

    更新:如果您只需要结果序列中的唯一 id,那么在讨人喜欢的序列之后也应用 Enumerable.Distinct

    【讨论】:

      【解决方案3】:

      类似:

      foreach(var nodeId in nodeIds)
      {
          foreach(var id in nodeId)
          {
              //do stuff with id
          }
      }
      

      nodeIds[0][0]
      

      【讨论】:

        【解决方案4】:

        例如:

        foreach(int[] items in nodeIds)
          foreach(int item in items)
            // do something with item
        

        【讨论】:

          【解决方案5】:

          如果要获取列表中所有数组的所有整数,可以使用IEnumerableSelectMany方法:

          IEnumerable<int> allIDs = nodeIds.SelectMany(a => a);
          

          您可以使用foreach枚举结果或对结果进行聚合等。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多