【问题标题】:How does one convert from an IEnumerable to IEnumerable<T>?如何从 IEnumerable 转换为 IEnumerable<T>?
【发布时间】:2015-03-20 22:27:18
【问题描述】:

假设我在设计时知道类型,有没有办法在没有 reflection 的情况下从 IEnumerable 获取 IEnumerable&lt;T&gt;

我有这个

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&lt;DirectoryEntry&gt;

【问题讨论】:

    标签: c# active-directory parallel-processing task-parallel-library


    【解决方案1】:

    实现这一点的方法是使用.Cast&lt;T&gt;() extension method

    Parallel.ForEach(de.Children.Cast<DirectoryEntry>(), 
        (DirectoryEntry child) => { // long running code on each child });
    

    实现此目的的另一种方法是使用.OfType&lt;T&gt;() extension method

    Parallel.ForEach(de.Children.OfType<DirectoryEntry>(), 
        (DirectoryEntry child) => { // long running code on each child });
    

    .Cast&lt;T&gt;().OfType&lt;T&gt;() 之间存在细微差别

    OfType(IEnumerable) 方法只返回那些元素 可以转换为类型 TResult 的源。而是收到一个 如果元素不能转换为 TResult 类型,则异常,请使用 演员表(IEnumerable)。

    --MSDN

    这个链接on the MSDN forums 让我朝着正确的方向前进。

    【讨论】:

    • @KooKiz:但如果你知道每个元素都是DirectoryEntry,那也没有意义。 OfType 过滤和强制转换,所以如果你需要过滤使用OfType 否则Cast
    • @TimSchmelter 不知何故,我一直认为OfTypeCast 快。不要问我为什么。无论如何,我刚刚搜索了一下,发现Cast 更快。所以确实,我的话毫无意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多