Pete
Pete

Reputation: 1

LINQ get list from list by comparing enum

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

Answers (2)

Jon Skeet
Jon Skeet

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:

  • 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

Upvotes: 3

Patrick Hofman
Patrick Hofman

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

Related Questions