FirstOrDefault returns NullReferenceException if no match is found

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

提交回复
热议问题