【发布时间】:2015-03-24 12:08:15
【问题描述】:
我有一个看起来像这样的二维字节数组:
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 将索引返回到设置了最多 1 的行,在上面的示例中应该返回 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);
}
所以,我的问题是:
- 如何使用 LINQ 来解决这个问题,在这里使用 LINQ 会比使用上面的非 LINQ 代码效率低吗?
- 是否可以使用 PLINQ 解决此问题?或者,假设每行至少有 1,000 列,直接使用任务并行库 (TPL) 并将每行中 1 的数量拆分到单独的线程中会更有效吗?
【问题讨论】:
-
必须是
byte[,]还是IEnumerable<IEnumerable<byte>>或byte[][]? -
@Los Firjoles 我可以让它成为 IEnumerable
> 或 byte[][] 的锯齿状数组。 -
我假设您已经看过像 stackoverflow.com/questions/3150678/… 和 stackoverflow.com/questions/18673822/… 这样的答案...哪些建议不起作用/为什么?
-
@Alexei Levenkov 我确实看到了第一个链接,但不确定我是否看到了第二个。其他问题/解决方案没有任何分组代码,而且我还不是 LINQ 专家。在发布之前花了一些时间进行研究并试图弄清楚它如何与 LINQ 一起工作。非常感谢以下解决方案。我现在要做的是在上面的循环代码中添加一些并行代码,并将其与下面的每个解决方案进行比较,看看哪个最快。我会在几天后有更多时间时用结果更新 OP。