Sequence contains no elements error but I want to check for null

By : Alex
Source: Stackoverflow.com
Question!

I have the following problem:

public Boolean Exists(String userName)
{
    IRepository<User> = new UserRepository();
    User user = userRepository.First(u => u.Name == userName);

    if (user == null) return false;

    // Exists!
    return true;
}

The problem is now, that I can't check the User object for null. Before I get there, I get an InvalidOperationException saying "The sequence contains no elements".

This seems really weird to me, especially as I don't want to establish control flow with exceptions (e.g. encapsulate in try..catch and return true/false in the respective parts).

What's going on here? Is this normal or is there something wrong with my respository (hint?!)

By the way, this code works perfectly when the element that I'm looking for exists (the User is retrieved etc.). It only doesn't work when there is no match.

By : Alex


Answers

Use .FirstOrDefault() to prevent that error

By : ichiban


Try changing .First() to .FirstOrDefault().



Use FirstOrDefault instead of First. This will return null in the face of an empty collection.

IRepository<User> = new UserRepository();
User user = userRepository.FirstOrDefault(u => u.Name == userName);
By : JaredPar


This video can help you solving your question :)
By: admin