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

后端 未结 6 1385
温柔的废话
温柔的废话 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 04:01

    The 2D array doesn't have any built in way of iterating over a row or column. It's not too difficult to create your own such method though. See this class for an implementation which gets an enumerable for row and column.

    public static class LINQTo2DArray
    {
        public static IEnumerable Row(this T[,] Array, int Row)
        {
            for (int i = 0; i < Array.GetLength(1); i++)
            {
                yield return Array[Row, i];
            }
        }
        public static IEnumerable Column(this T[,] Array, int Column)
        {
            for (int i = 0; i < Array.GetLength(0); i++)
            {
                yield return Array[i, Column];
            }
        }
    }
    

    You can also flatten the array usinga.Cast() but you would then loose all the info about columns/rows

提交回复
热议问题