简体   繁体   English

如何处理从 lambda 选择返回的空值?

[英]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.

相关问题 如何处理从 webgrid 中的控制器返回的列值的空异常? - How to handle null exception for column values returned from controller in webgrid? 在Lambda表达式中的MVC中的视图中处理空值 - Handle null value in view in mvc in lambda expression 如何检索从sqlstoredprocedure返回的单个值? - How can I retrieve single value returned from sql storedprocedure? 如何处理从LINQ to SQL中的存储过程返回的NULLable Int列 - How can I handle a NULLable Int column returned from a stored procedure in LINQ to SQL 如何处理从存储过程返回到C#调用程序的多个字段? - How can I handle multiple fields returned from my stored procedure to a C# calling program? 如何从数据库datareader解析值并处理可能的NULL值? - How to parse value from database datareader and handle possible NULL value? 如何防止Lambda LINQ表达式添加空值 - How to prevent Lambda LINQ expression from adding a null value 此lambda变量如何为null? - How can this lambda variable be null? 如何从 guid null 中使系统为空值? - How can I make the system empty value from the guid null? 如何防止用户保存具有 null 值的记录? - How can I prevent a user from saving a record with a null value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM