DenaliHardtail
DenaliHardtail

Reputation: 28296

How do I handle no results returned from a LINQ query?

The following LINQ query works fine except when there are no results to return. Then an InvalidOperationException is thrown.

What is the best way to handle this? How do I test for the existance of a result and move along if there is none? I thought about a try-catch but felt there must be a more elegant solution.

In this example, I'm only expecting the Id of the first result. There may be other case where I want the entire object returned.

var drId = dcDest.drs.Where(dr => dr.ContactID == contactId)
                      .Select(dr => dr.Id).First();

int xId = drId;

Upvotes: 0

Views: 2468

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39277

You should use SingleOrDefault().

FirstOrDefault() could work too but really you are saying that there should only be one in the collection which makes 'SingleOrDefault()' the more proper choice (it will throw an exception if there is more than one).

If on the other hand you are expecting a sequence but need to handle the case when no elements are returned you can also use DefaultIfEmpty() to return a default value when the sequence is empty. See http://msdn.microsoft.com/en-us/library/bb355419.aspx

What behavior do you want when it is empty? An id of Zero or something else?

Upvotes: 3

Related Questions