Search code examples
c#derived-class

In C#, get a List<DerivedClass> from a List<BaseClass>


I have a Class, Food which has two derived classes: Meat and Vegetables.

If I have a List of Foods, I can get a (sub)list of Foods that are Meat using

List<Food> allTheFood = GetListOfFood();
List<Food> justTheMeats = allTheFood.Where(x => x is Meat);

But this gives me a list of type Food (where they all happen to be Meat), rather than a list of Meat.

Obviously, I could create a new empty List and then do a foreach and cast every individual item from justTheMeats from Food to Meat and add them into the new List, but that seems a convoluted approach.

Is there a nicer/easier/cleaner way to do this?

Thanks


Solution

  • Yes, use linq OfType

    var justTheMeats = allTheFood.OfType<Meat>().ToList();