问题描述
这是我的代码:
string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID)).Value.DisplayName;
如果x.Value.ID
与options.ID
匹配,则代码工作正常.但是,如果没有,我会得到一个NullReferenceException
.
The code works fine if x.Value.ID
matches options.ID
. However, I get a NullReferenceException
if it doesn't.
推荐答案
FirstOrDefault
返回类型的默认值.对于引用类型为null
.多数民众赞成在例外的原因.
FirstOrDefault
returns the default value of a type if no item matches the predicate. For reference types that is null
. Thats the reason for the exception.
所以您只需要先检查null
:
string displayName = null;
var keyValue = Dictionary
.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue != null)
{
displayName = keyValue.Value.DisplayName;
}
但是,如果要搜索值,那么词典的关键字是什么? Dictionary<tKey,TValue>
用于通过键查找值.也许您应该重构它.
But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue>
is used to find a value by the key. Maybe you should refactor it.
另一种选择是提供DefaultIfEmpty
的默认值:
Another option is to provide a default value with DefaultIfEmpty
:
string displayName = Dictionary
.Where(kv => kv.Value.ID == long.Parse(options.ID))
.Select(kv => kv.Value.DisplayName) // not a problem even if no item matches
.DefaultIfEmpty("--Option unknown--") // or no argument -> null
.First(); // cannot cause an exception
这篇关于如果找不到匹配的内容,则FirstOrDefault返回NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!