Two dimensional array slice in C#

后端 未结 3 1593
梦如初夏
梦如初夏 2020-12-03 21:18

I\'m looking to slice a two dimensional array in C#.

I have double[2,2] prices and want to retrieve the second row of this array. I\'ve tried prices[1,], but I have

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 21:44

    There's no direct "slice" operation, but you can define an extension method like this:

    public static IEnumerable SliceRow(this T[,] array, int row)
    {
        for (var i = 0; i < array.GetLength(0); i++)
        {
            yield return array[i, row];
        }
    }
    
    double[,] prices = ...;
    
    double[] secondRow = prices.SliceRow(1).ToArray();
    

提交回复
热议问题