It looks like you really just want Where instead of SelectMany:
public List<IAnimal> GetListOfAnimalsByType(IAnimal.AnimalType animalType)
{
return animalList.Where(ani => ani.Type == animaleType).ToList();
}
SelectMany is used to extract one sequence from each element within an original sequence, and usually "flatten" the resulting sequences together... whereas Where is used for filtering.
Additionally:
- The
ToList() call is necessary because LINQ returns IEnumerable<T> or IQueryable<T>, not List<T>
- Your
if statement is unnecessary as sequence-producing LINQ operators (e.g. Where, Select etc never return null; they'll return an empty sequence if necessary
- Even if the call could return null, you're returning the value of
animalTypeList in both cases... "if the value is null, return null, otherwise return the value"... so you could still just return the result of the call
IAnimal, it sounds like an interface but obviously it's not since you can't define a nested type within an interface.