31

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.

amit_g
  • 30,880
  • 8
  • 61
  • 118
Alex
  • 75,813
  • 86
  • 255
  • 348

4 Answers4

61

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);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    @Tomas, I actually got in ahead of you but I made a post answer edit to actually include a code sample. The second edit was 2 seconds behind :) – JaredPar Jun 03 '09 at 00:27
  • Thats true Jared got in first :D (by 2 seconds.. it was showing Jared 48 secs ago and Tomas 46 secs ago). Thank you Gentlemen!!!! – Alex Jun 03 '09 at 00:28
23

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

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
12

Use .FirstOrDefault() to prevent that error

ichiban
  • 6,162
  • 3
  • 27
  • 34
0

FirstOrDefault is very important. But for your exact use, you can also say Any:

public bool Exists(string userName)
{
    IRepository<User> userRepository = new UserRepository();
    return userRepository.Any(u => u.Name == userName);
}
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181