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;}
}
Use OfType<T>
:
var onlyChildren = acol.OfType<B>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With