c# - FilterAndCast Linq 扩展方法

标签 c# linq

我在某些地方会做这样的事情:

var listOfBaseClasses = new List<BaseClass>() { ... }
var things = listOfBaseClasses
    .Where(t => t is Thing)
    .Cast<Thing>()
    .ToList()

我意识到这有点代码味道,这就是支持别人代码的生活。

我想创建一个扩展方法来组合 Where 和 Cast 扩展方法。这是我目前所拥有的..

public static IEnumerable<TResult> FilterAndCast<TResult>(this IEnumerable source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }

    foreach (var item in source)
    {
        if (item.GetType() == typeof(TResult))
        {
            yield return (TResult)item;
        }
    }
}

有更好的方法吗?

最佳答案

是的,只需使用 OfType<T> :

Filters the elements of an IEnumerable based on a specified type.

var things = listOfBaseClasses.OfType<Thing>.ToList()

关于c# - FilterAndCast Linq 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22537076/

相关文章:

c# - 使用 LINQ 通过单个查询获取外键表

c# - Linq Group 结果到对象

c# - 如何将带条件的嵌套 foreach 循环转换为 LINQ

c# - 是否可以通过反射调用 "Select"方法

c# - 从 app.config 获取 ConnectionString

sql - 为什么此 LINQ 查询将值 1 分配给数据库中的 NULL 值?

c# - 不等待异步方法调用可以吗?

c# - 如何修复 "Pinvoke stack imbalance detected"错误

c# - 如何将通用集合转换为通用祖先集合?

c# - C# 编译器的图像调试选项如何影响 .NET JIT 编译性能(包括动态方法)?