FirstOrDefault returns NullReferenceException if no match is found

后端 未结 7 2046
广开言路
广开言路 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 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
    

提交回复
热议问题