Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only subclasses from collection with Linq

The below code is already working but I am interested if there is a better way of doing this. In short, an IEnumerable contains instance of type A and B (inherits A). I would like to select only the instances of type B from the collection and sum one of their properties.

Here is the code that I have already but I am interested if the Linq statement can be done in a different way - currently it will cast it twice if I am not mistaken (once in the Where and once in the 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;}
    }
like image 846
sTodorov Avatar asked Dec 24 '22 23:12

sTodorov


1 Answers

Use OfType<T>:

var onlyChildren = acol.OfType<B>();
like image 132
Pieter Witvoet Avatar answered Dec 27 '22 17:12

Pieter Witvoet