[英]How can i handle a null value returned from a lambda selection?
I am using the following lambda selection我正在使用以下 lambda 选择
if (users.Any(x => x.userId.ToString() == id))
{
var user = _users.First(x => x.userId.ToString() == id);
_users.Remove(user);
}
//use entitybase to setup the user and its id.i have left that bit out
_users.Add(user)
There are no values in the users list that match id so the line用户列表中没有与 id 匹配的值,因此该行
users.Any(x => x.userId.ToString() == id // gives a "Object reference exception"
Is there a selection in lambda i can use that takes care of nulls.我可以使用 lambda 中的选择来处理空值。
I'd suggest to instead of .ToString()
, parse id
to the type userId
is.我建议而不是
.ToString()
,将id
解析为userId
类型。
Then:然后:
// this is compeletely unneccessary
//if (users.Any(x => x.userId.ToString() == id))
//{
// vv this assumes that if x is not null, property `userId` is required, so cannot be null
var user = _users.FirstOrDefault(x => !(x is null) && x.userId == id);
if(!(user is null)) // C# 9 : if( user is not null )
{
_users.Remove(user);
}
//}
Alternative Linq:替代 Linq:
var user = _users.Where(x => !(x is null)).FirstOrDefault(x => x.userId ==id);
Not sure which one would perform better.不确定哪一个会表现得更好。 I'd probably benchmark this.
我可能会对此进行基准测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.