我在某些地方会做这样的事情:
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/