4

我在弄清楚如何Parallel.ForEach使用二维字符串数组调用 时遇到了一些麻烦:

string[,] board = new string[,]{
        {"A", "B", "C", "D", "E" },
        {"F", "G", "H", "I", "J"},
        {"K", "L", "M", "N", "O"},
        {"0", "1", "2", "3", "4"}};

Parallel.ForEach(board, row =>
    {
        for (int i = 0; i < row.Length; ++i)
        {
            // find all valid sequences
        }
    });

如果我没有明确指定类型,我会收到以下错误:

无法从用法中推断方法“System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)”的类型参数。尝试明确指定类型参数。

明确指定类型参数的正确方法是什么?

4

2 回答 2

6

你的问题是二维数组没有实现IEnumerable<one-dimensional-array>. (它确实实现IEnumerable了 ,但它是一个IEnumerable“扁平化”数组的字符串。)你可以做两件事:

  • 将 更改string[,]为锯齿状数组数组,string[][].

  • 实现您自己的扩展方法,该方法迭代二维数组并将其转换为IEnumerable<one-dimensional-array>.

于 2010-07-20T01:10:00.843 回答
3

您仍然应该能够使用多维数组来完成这项工作,只需使用Parallel.For而不是Parallel.ForEach

string[,] board = new string[,] {
    {"A", "B", "C", "D", "E" },
    {"F", "G", "H", "I", "J"},
    {"K", "L", "M", "N", "O"},
    {"0", "1", "2", "3", "4"}
};

int height = board.GetLength(0);
int width = board.GetLength(1);

Parallel.For(0, height, y =>
    {
        for (int x = 0; x < width; ++x)
        {
            string value = board[y, x];
            // do whatever you need to do here
        }
    }
);
于 2010-07-20T01:28:35.613 回答