如何在SQL#中将foreach转换为Parallel.Foreach

pet*_*ter -2 .net c# foreach multithreading .net-framework-version

我有一个foreach如下所示的循环

ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);

foreach (string item in list)
{
}
Run Code Online (Sandbox Code Playgroud)

Parallel.Foreach没有运气就转换成如下所示

ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);

Parallel.ForEach(list.ToArra(), item => 
{
    if (item.StartsWith("GExport_") &&(!item.ToUpper().Contains("DUM")))
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

它抛出错误,如项目不包含StartsWith()扩展方法.怎么解决?

Dav*_*haw 7

这是因为foreach在转换中的项目ArrayList,以stringobject.a中的所有项ArrayListobject在编译时,并且object没有调用的方法StartsWith.

在这种情况下:

foreach (string item in list)
Run Code Online (Sandbox Code Playgroud)

item被转换为stringobject.

要做同样的事情,你需要自己进行转换,例如

Parallel.ForEach(list.OfType<string>().ToArray(), item ....
Run Code Online (Sandbox Code Playgroud)

或者如果你想在运行时失败,.Cast<string>而不是OfType你的非字符串实例list.

或者使用通用列表,List<String>以避免运行时转换.

  • 小问题 - 更相同,它应该是`.Cast <string>`而不是`OfType <string>` - 假设我们想要在我们发现非字符串时遇到困难和快速失败(就像原始代码那样) `list` (2认同)