[c#] 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 related to c# lambda

The answer is


To add to the solutions, here is a LINQ statement that might help

Utilities.DIMENSION_MemTbl.Where(a => a.DIMENSION_ID == format.ContentBrief.DimensionID).Select(a=>a.DIMENSION1).DefaultIfEmpty("").FirstOrDefault();

The result will be an empty string if the result of the query is a null..


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)
                    .DefaultIfEmpty("Unknown")
                    .First();

Simply use the question mark trick for null checks:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";

That is because FirstOrDefaultcan return null causing your following .Value to cause the exception. You need to change it to something like:

var myThing = things.FirstOrDefault(t => t.Id == idToFind);

if(myThing == null)
    return; // we failed to find what we wanted
var displayName = myThing.DisplayName;

Use the SingleOrDefault() instead of FirstOrDefault().


i assume you are working with nullable datatypes, you can do something like this:

var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;