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

后端 未结 6 1453
温柔的废话
温柔的废话 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条回答
  •  旧时难觅i
    2021-02-06 03:51

    LINQ to Objects is based on the IEnumerable Interface, i.e. a one-dimensional sequence of values. This means it doesn't mix well with n-dimensional data structures like non-jagged arrays, although it's possible.

    You can generate one-dimensional sequence of integers that index into the n-dimensional array:

    int rowSum = Enumerable.Range(0, a.GetLength(1)).Sum(i => a[1, i]);
    
    int colSum = Enumerable.Range(0, a.GetLength(0)).Sum(i => a[i, 1]);
    

提交回复
热议问题