如何使用具有二维数组的LINQ

Bob*_*yan 3 c# linq arrays plinq

我有一个二维字节数组,看起来像这样:

0 0 0 0 1

1 1 1 1 0

0 0 1 1 1

1 0 1 0 1

数组中的每个值只能是0或1.上面的简化示例显示了4行,每行有5列.我试图弄清楚如何使用LINQ将索引返回到具有最大数量1s的行,在上面的示例中应该返回1.

以下非LINQ C#代码解决了这个问题:

static int GetMaxIndex(byte[,] TwoDArray)
{
   // This method finds the row with the greatest number of 1s set.
   //
   int NumRows = TwoDArray.GetLength(0);
   int NumCols = TwoDArray.GetLength(1);
   int RowCount, MaxRowCount = 0, MaxRowIndex = 0;
   //
   for (int LoopR = 0; LoopR < NumRows; LoopR++)
   {
      RowCount = 0;
      for (int LoopC = 0; LoopC < NumCols; LoopC++)
      {
         if (TwoDArray[LoopR, LoopC] != 0)
            RowCount++;
      }
      if (RowCount > MaxRowCount)
      {
         MaxRowCount = RowCount;
         MaxRowIndex = LoopR;
      }
   }
   return MaxRowIndex;
}

static void Main()
{
   byte[,] Array2D = new byte[4, 5] { { 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 0 }, { 0, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1 } };
   int MaxInd = GetMaxIndex(Array2D);
   Console.WriteLine("MaxInd = {0}", MaxInd);
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:

  1. 如何使用LINQ来解决这个问题,并且在这里使用LINQ会比使用上面的非LINQ代码效率低吗?
  2. 用PLINQ解决这个问题有可能吗?或者,将任务并行库(TPL)直接用于上述代码并将每行中1的数量计数拆分为单独的线程会更高效,假设每行至少有1,000列吗?

slv*_*ron 5

使用LINQ的多维数组很难处理,但是你可以这样做:

var arr = new [,] { { 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 0 }, { 0, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1 } };

var data =
    Enumerable.Range(0, 4)
        .Select(
            row =>
                new
                {
                    index = row,
                    count = Enumerable.Range(0, 5).Select(col => arr[row, col]).Count(x => x == 1)
                })
        .OrderByDescending(x => x.count)
        .Select(x => x.index)
        .First();
Run Code Online (Sandbox Code Playgroud)