Linq expression over a list of derived types

I am trying to write a Linq expression that checks a property in a derived class, but the list consists of members from the base class. Sample code below. The second line of the Process method, starting with "var list", does not compile, but I'm not sure which syntax I should use to make it valid?

public class Manager { public void Process() { Base[] stuff = { new Derived() { Id = "1", Name = "me" } }; var list = stuff.Where<Derived>(d => d.Name == "me"); } } public class Base { public string Id { get; set; } } public class Derived : Base { public string Name { get; set; } } 
+4
source share
1 answer

If you know that only Derived has a list, you can use the Cast<T> method:

 var list = stuff.Cast<Derived>().Where(d => d.Name == "me"); 

If there are only a few Derived , you can use OfType<T> :

 var list = stuff.OfType<Derived>().Where(d => d.Name == "me"); 

In this case, non- Derived objects will be skipped.

+7
source

All Articles