FirstOrDefault returns NullReferenceException if no match is found

后端 未结 7 2040
广开言路
广开言路 2021-02-05 00:26

Here is my code:

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

The code works

相关标签:
7条回答
  • 2021-02-05 00:44

    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
    
    0 讨论(0)
  • 2021-02-05 00:53

    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();
    
    0 讨论(0)
  • 2021-02-05 00:55

    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";
    
    0 讨论(0)
  • 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..

    0 讨论(0)
  • 2021-02-05 01:05

    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;
    
    0 讨论(0)
  • 2021-02-05 01:05

    Use the SingleOrDefault() instead of FirstOrDefault().

    0 讨论(0)
提交回复
热议问题