How to use LINQ with a 2 dimensional array

前端 未结 5 1485
深忆病人
深忆病人 2020-12-21 08:38

I have a 2-dimensional byte array that looks something like this:

0 0 0 0 1

1 1 1 1 0

0 0 1 1 1

1 0 1 0 1

5条回答
  •  情书的邮戳
    2020-12-21 09:06

    // This code is extracted from
    // http://www.codeproject.com/Articles/170662/Using-LINQ-and-Extension-Methods-in-C-to-Sort-Vect
    private static IEnumerable ConvertToSingleDimension(T[,] source)
    {
        T[] arRow;
        for (int row = 0; row < source.GetLength(0); ++row)
        {
            arRow = new T[source.GetLength(1)];
            for (int col = 0; col < source.GetLength(1); ++col)
                arRow[col] = source[row, col];
            yield return arRow;
        }
    }
    
    
    // Convert byte[,] to anonymous type {int index, IEnumerable} for linq operation
    var result = (from item in ConvertToSingleDimension(Array2D).Select((i, index) => new {Values = i, Index = index})
                 orderby item.Values.Sum(i => i) descending, item.Index
                 select item.Index).FirstOrDefault();
    

提交回复
热议问题