Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 358
Alex Avatar asked Jun 03 '09 00:06

Alex


People also ask

Why do sequences contain no elements?

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() . This can also be caused by the following commands: FirstAsync()

What exception does SingleOrDefault throw?

SingleOrDefault<TSource>(IEnumerable<TSource>) Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

What is the default value of SingleOrDefault?

Default value for the element is default(type). For classes default value is null.


2 Answers

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); 
like image 90
JaredPar Avatar answered Sep 25 '22 13:09

JaredPar


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

like image 44
Tomas Aschan Avatar answered Sep 24 '22 13:09

Tomas Aschan