【发布时间】:2014-03-20 23:11:34
【问题描述】:
我在一些地方会做这样的事情:
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;
}
}
}
有没有更好的方法来做到这一点?
【问题讨论】: