FirstOrDefault returns NullReferenceException if no match is found

后端 未结 7 2041
广开言路
广开言路 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;
    
    0 讨论(0)
提交回复
热议问题