使用Linq从集合中仅选择子类

sTo*_*rov 3 c# linq optimization inheritance

下面的代码已经开始工作,但我感兴趣的是,如果有更好的方法可以做到这一点.简而言之,IEnumerable包含类型A和B的实例(继承A).我想从集合中只选择类型B的实例,并将它们的一个属性相加.

这是我已经拥有的代码,但我感兴趣的是Linq语句是否可以以不同的方式完成 - 如果我没有弄错,它会抛出两次(一次在Select中,一次在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;}
    }
Run Code Online (Sandbox Code Playgroud)

Pie*_*oet 7

用途OfType<T>:

var onlyChildren = acol.OfType<B>();
Run Code Online (Sandbox Code Playgroud)