FirstOrDefault returns NullReferenceException if no match is found

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

    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;
    

提交回复
热议问题