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

后端 未结 6 1454
温柔的废话
温柔的废话 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

    To add to dtb's solution, a more general way of iterating over all items of the array would be:

    int[,] b = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
    
    var flattenedArray = Enumerable.Range(0, b.GetLength(0))
                         .SelectMany(i => Enumerable.Range(0, b.GetLength(1))
                             .Select(j => new { Row = i, Col = j }));
    

    And now:

    var rowSum2 = flattenedArray.Where(t => t.Row == 1).Sum(t => b[t.Row, t.Col]);
    var colSum2 = flattenedArray.Where(t => t.Col == 1).Sum(t => b[t.Row, t.Col]);
    

    Of course this is ultra-wasteful as we are creating coordinate tuples even for those items that we will end up filtering out with Where, but if you don't know what the selection criteria will be beforehand this is the way to go (or not -- this seems more like an excercise than something you 'd want to do in practice).

    I can also imagine how this might be extended for arrays of any rank (not just 2D) using a recursive lambda and something like Tuple, but that crosses over into masochism territory.

提交回复
热议问题