初始化VAR为null [英] Initialize var to null
问题描述
我已经看到了如何初始化 VAR为null。这在我的情况没有帮助。我有
I have seen how to initialize var to null. This does not help in my situation. I have
string nuller = null;
var firstModel = nuller;
if(contextSelectResult.Count() > 0)
firstModel = contextSelectResult.First();
我得到错误
I get error
无法隐式转换类型
'SomeNamespace.Model.tableName'到'字符串'。
Cannot implicitly convert type 'SomeNamespace.Model.tableName' to 'string'.
我想避免尝试/赶超 InvalidOperation
为第一()时,没有先存在它的昂贵
。所以,我怎么能得到过去在这里的范围问题。
I am trying to avoid try/catching InvalidOperation
for First()
when no first exists as its expensive. So, how can I get past the scope issue here?
推荐答案
只需使用的 FirstOrDefault()
代替。整点 FirstOrDefault
是如果它存在返回序列的第一个元素,否则该元素类型的默认值(即所有的引用类型为null)。
Simply use FirstOrDefault()
instead. The whole point of FirstOrDefault
is to return the first element of the sequence if it exists, or the default value of the element type (i.e. null for all reference types) otherwise.
请注意,在那里你想检查任何元素的存在,使用任何()
有时可其他案件比更有效计数()> 0
- 这取决于具体上下文,但国际海事组织是你在找什么呢表达一个简单的方法
Note that in other cases where you wish to check for the existence of any elements, using Any()
can sometimes be more efficient than Count() > 0
- it depends on the exact context, but IMO it's a simpler way of expressing what you're looking for anyway.
这篇关于初始化VAR为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!