Array operations with n-dimensional array using LINQ (C#)

后端 未结 6 1457
温柔的废话
温柔的废话 2021-02-06 03:23

Assume we have a jagged array

int[][] a = { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 }, new[] { 9, 10, 11, 12 } };

To get a sum of second row a

6条回答
  •  甜味超标
    2021-02-06 03:47

    The simplest LINQ only approach I can see to do these kinds of row and column operations on a two dimensional array is to define the following lookups:

    var cols = a
        .OfType()
        .Select((x, n) => new { x, n, })
        .ToLookup(xn => xn.n % a.GetLength(1), xn => xn.x);
    
    var rows = a
        .OfType()
        .Select((x, n) => new { x, n, })
        .ToLookup(xn => xn.n / a.GetLength(1), xn => xn.x);
    

    Now you can simply do this:

    var firstColumnSum = cols[0].Sum();
    

    As for n-dimensional, it just gets too painful... Sorry.

提交回复
热议问题