![](/img/trans.png)
[英]How to convert an IEnumerable<IEnumerable<T>> to a IEnumerable<T>
[英]How does one convert from an IEnumerable to IEnumerable<T>?
假设我在设计时知道类型,有没有办法从IEnumerable
获取IEnumerable<T>
而没有反射 ?
我有这个
foreach(DirectoryEntry child in de.Children)
{
// long running code on each child object
}
我试图像这样启用并行化
Parallel.ForEach(de.Children,
(DirectoryEntry child) => { // long running code on each child });
但这不起作用,因为de.Children的类型为DirectoryEntries
。 它实现IEnumerable
但不实现IEnumerable
IEnumerable<DirectoryEntry>
。
实现此目的的方法是使用.Cast<T>()
扩展方法 。
Parallel.ForEach(de.Children.Cast<DirectoryEntry>(),
(DirectoryEntry child) => { // long running code on each child });
实现此目的的另一种方法是使用.OfType<T>()
扩展方法 。
Parallel.ForEach(de.Children.OfType<DirectoryEntry>(),
(DirectoryEntry child) => { // long running code on each child });
.Cast<T>()
和.OfType<T>()
之间有细微的区别
OfType(IEnumerable)方法仅返回源中可以转换为TResult类型的那些元素。 如果无法将元素强制转换为TResult类型,则要接收异常,请使用Cast(IEnumerable)。
-MSDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.