0

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;
    }
}
1
  • 2
    also, you should reconsider your naming of IAnimal, it sounds like an interface but obviously it's not since you can't define a nested type within an interface. Commented Nov 13, 2014 at 12:33

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

But if he want to return null, he can change condition to animalTypeList.Any(), because this list will never be null.
@PawełReszka: Then just check if there is any item. Why would you want to return null anyway?
No idea;) I just wanted to point that your function will never return null, but OP in some cases wanted to return null. I just wanted to clear out to OP, that he won't get null.
2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.