Reputation: 1
I am trying to get a list of objects from a list by comparing an enum that is passed into the method.
public List<IAnimal> GetListOfAnimalsByType(IAnimal.AnimalType animalType)
{
List<IAnimal> animalTypeList = animalList.SelectMany(ani => ani.Type == animaleType);
if(animalTypeList != null)
{
return animalTypeList;
}
else
{
return null;
}
}
Upvotes: 0
Views: 96
Reputation: 1503839
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:
ToList()
call is necessary because LINQ returns IEnumerable<T>
or IQueryable<T>
, not List<T>
if
statement is unnecessary as sequence-producing LINQ operators (e.g. Where
, Select
etc never return null; they'll return an empty sequence if necessaryanimalTypeList
in both cases... "if the value is null, return null, otherwise return the value"... so you could still just return the result of the callUpvotes: 3
Reputation: 157136
You should use ToList
to get a list out of the SelectMany
. Also, a Where
would suffice.
The methods SelectMany
and Where
return a IEnumerable<TSource>
, which isn't a List<T>
of course. That's why you need to call ToList
.
List<IAnimal> animalTypeList = animalList
.Where(ani => ani.Type == animaleType)
.ToList();
Upvotes: 2