如何使用多维数组调用 Parallel.ForEach
我在弄清楚如何使用 2D 字符串数组调用 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)' 不能 从使用情况推断。尝试 指定类型参数 明确地。
显式指定类型参数的正确方法是什么?
I'm having a little trouble figuring out how to call the Parallel.ForEach
with a 2D array of strings:
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
}
});
If I don't specify the type explicitly I get the following error:
The type arguments for method
'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable,
System.Action)' cannot be
inferred from the usage. Try
specifying the type arguments
explicitly.
What's the proper way to specify the type arguments explicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您面临的问题是二维数组没有实现
IEnumerable<一维数组>
。 (它确实实现了 IEnumerable,但它是一个“扁平化”数组的字符串的 IEnumerable。)您可以执行两件事:更改
string[ ,]
为锯齿状数组,string[][]
。实现您自己的扩展方法,迭代二维数组并将其转换为
IEnumerable<一维数组>
。The problem for you is that 2-dimensional arrays do not implement
IEnumerable<one-dimensional-array>
. (It does implementIEnumerable
, but it's anIEnumerable
of strings that "flattens" the array.) You can do two things:Change the
string[,]
to a jagged array-of-arrays,string[][]
.Implement your own extension method that iterates over a two-dimensional array and turns it into an
IEnumerable<one-dimensional-array>
.您仍然应该能够使用多维数组来完成此操作,只需使用
Parallel.For
而不是Parallel.ForEach
:You should still be able to make this work with a multi-dimensional array, just using
Parallel.For
instead ofParallel.ForEach
: