FirstOrDefault returns NullReferenceException if no match is found

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

提交回复
热议问题