如何调用并行。ForEach与多维数组
-
17-09-2020 - |
题
我在想怎么叫 Parallel.ForEach
用2D字符串数组:
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
}
});
如果我没有明确指定类型,我会得到以下错误:
方法的类型参数 '系统。线程。任务。平行。ForEach(系统。收藏品。通用的。IEnumerable碌录潞陆, 系统。动作)'不能 用法推断。试试 指定类型参数 明确地说。
显式指定类型参数的正确方法是什么?
解决方案
你的问题是二维数组没有实现 IEnumerable<one-dimensional-array>
.(它确实实现了 IEnumerable
, ,但它是一个 IEnumerable
"扁平化"数组的字符串。 你可以做两件事:
更改
string[,]
到锯齿阵列,string[][]
.实现自己的扩展方法,该方法迭代二维数组并将其转换为
IEnumerable<one-dimensional-array>
.
其他提示
您应该仍然能够使用多维数组进行此工作,只需使用 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
}
}
);
不隶属于 StackOverflow