FirstOrDefault returns NullReferenceException if no match is found

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

    You can use a combination of other LINQ methods to handle not matching condition:

    var res = dictionary.Where(x => x.Value.ID == someID)
                        .Select(x => x.Value.DisplayName)
                        .DefaultIfEmpty("Unknown")
                        .First();
    

提交回复
热议问题