下面的代码已经可以工作了,但我很想知道是否有更好的方法来做到这一点。简而言之,IEnumerable 包含类型 A 和 B(继承 A)的实例。我想从集合中仅选择类型 B 的实例并对它们的一个属性求和。
这是我已经拥有的代码,但我对是否可以用不同的方式完成 Linq 语句很感兴趣——如果我没记错的话,目前它将转换两次(一次在 Where 中,一次在 Select 中):
void Main()
{
List<A> acol = new List<A>();
acol.Add(new A{id = 1});
acol.Add(new B{id = 2, name = "b", anotherID = 1});
//Can the Where and Select be optimized/done in different way
var onlyChildren = acol.Where(i => i is B).Select(c => c as B);
onlyChildren.Dump();
onlyChildren.Sum(c => c.anotherID).Dump();
}
class A
{
public int id {get;set;}
}
class B:A
{
public string name {get;set;}
public int anotherID {get;set;}
}
最佳答案
使用 OfType<T>
:
var onlyChildren = acol.OfType<B>();
关于c# - 使用 Linq 仅从集合中选择子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019958/