FirstOrDefault returns NullReferenceException if no match is found


Here is my code:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID)).Value.DisplayName;

The code works fine if x.Value.ID matches options.ID. However, I get a NullReferenceException if it doesn't.

This question is tagged with c# lambda

~ Asked on 2014-01-16 12:00:18

The Best Answer is


FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.

So you just have to check for null first:

string displayName = null;
var keyValue = Dictionary
    .FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue  != null)
    displayName = keyValue.Value.DisplayName;

But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.

Another option is to provide a default value with DefaultIfEmpty:

string displayName = Dictionary
    .Where(kv => kv.Value.ID == long.Parse(options.ID))
    .Select(kv => kv.Value.DisplayName)   // not a problem even if no item matches
    .DefaultIfEmpty("--Option unknown--") // or no argument -> null
    .First();                             // cannot cause an exception

~ Answered on 2014-01-16 12:02:44


You can use a combination of other LINQ methods to handle not matching condition:

var res = dictionary.Where(x => x.Value.ID == someID)
                    .Select(x => x.Value.DisplayName)

~ Answered on 2014-01-16 12:11:23

Most Viewed Questions: