FirstOrDefault returns NullReferenceException if no match is found

C#Lambda

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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();

Solution 3 - C#

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;

Solution 4 - C#

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";

Solution 5 - C#

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..

Solution 6 - C#

This answer is for those of us who need a visual write up (like me :)

In the code screenshot below, a NullReferenceException will be thrown, the root cause is the ReferenceIdentification_02 property.

enter image description here

When debugging, we see that the orderLine.REF array, I am querying does not include a matching object whose ReferenceIdentificationQualifier_01 value == "RU", so at that point FirstOrDefault() return value is NULL

enter image description here

to prevent the NullReferenceException, I do a FirstOrDefault() on the orderLine.REF array first. If the returned value is not null then I retrieve the value.

enter image description here

Solution 7 - C#

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;

Solution 8 - C#

you can use with 'Where' statement with FirstOrDefault(). like this.

 var modelItem =  _dbcontext.ModelName.Where(n => n.NewsTagId == newsTag.Id).FirstOrDefault();

It returns first item if does not match query. It is better practice to check the NULL after query.

  if(modelItem == null)
  {
       return "Not Found."
  }
  else
  {
       // continue process
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaz MahatoView Question on Stackoverflow
Solution 1 - C#Tim SchmelterView Answer on Stackoverflow
Solution 2 - C#Konrad KokosaView Answer on Stackoverflow
Solution 3 - C#ZacheView Answer on Stackoverflow
Solution 4 - C#sɐunıɔןɐqɐpView Answer on Stackoverflow
Solution 5 - C#pat capozziView Answer on Stackoverflow
Solution 6 - C#Geovani MartinezView Answer on Stackoverflow
Solution 7 - C#A.T.View Answer on Stackoverflow
Solution 8 - C#MilanBogicView Answer on Stackoverflow