【问题标题】:How to use LINQ on a multidimensional array to 'unwind' the array?如何在多维数组上使用 LINQ 来“展开”数组?
【发布时间】:2023-03-10 07:44:01
【问题描述】:

考虑以下数组:

int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };

我想使用 LINQ 构造一个 IEnumerable,其中包含数字 2、1、3、4、6、5。

最好的方法是什么?

【问题讨论】:

  • 这是一个二维数组而不是数组数组(锯齿状数组)。
  • 你是对的......它是一个多维数组。
  • Convert 2 dimensional array 的可能重复项
  • 副本中有一个 linq 查询,但我会使用 foreach,因为 linq 查询非常不透明,而且 foreach 很清楚你在做什么。
  • 'var flatNumbers = numbers.Cast();'从链接的帖子中复制和修改。所有 LINQ

标签: c# .net linq multidimensional-array jagged-arrays


【解决方案1】:

也许很简单:

var all = numbers.Cast<int>();

Demo

【讨论】:

  • +1 来自我 - 在这种情况下,Cast 的开销比 OfType 少一些
  • 赞成。但无论哪种方式,我们都会得到 boxingunboxing,因为这会通过非通用的 IEnumerable 接口产生 object 盒子,这些盒子是由 Cast 取消装箱的。
【解决方案2】:

怎么样:

Enumerable
    .Range(0,numbers.GetUpperBound(0)+1)
    .SelectMany(x => Enumerable.Range(0,numbers.GetUpperBound(1)+1)
    .Select (y =>numbers[x,y] ));

或者整理一下。

var xLimit=Enumerable.Range(0,numbers.GetUpperBound(0)+1);
var yLimit=Enumerable.Range(0,numbers.GetUpperBound(1)+1);
var result = xLimit.SelectMany(x=> yLimit.Select(y => numbers[x,y]));

编辑修改后的问题......

var result = array.SelectMany(x => x.C);

【讨论】:

    【解决方案3】:

    使用简单的 foreach 从二维数组中获取数字:

    int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };
    foreach(int x in numbers)
    {
       // 2, 1, 3, 4, 6, 5.
    }
    

    LINQ(将 Linq 用于您的初始任务是一个很大的开销,因为将创建 OfTypeIterator 的 CastIterator(Tim 的答案)而不是简单的迭代数组)

    IEnumerable<int> query = numbers.OfType<int>();
    

    【讨论】:

    • 我需要使用 LINQ。我的问题更复杂......但我需要使用 LINQ。数组中的每个对象都有一个属性,该属性包含一个数组,我需要将其混入一个列表。
    • 请发布您的整个问题,因为您会得到不同的答案
    • 这可能是家庭作业,但它也可能是一个令人难以置信的复杂系统的最小工作示例,提问者不想打扰我们;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2010-10-17
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多