Reputation: 105
I am using the following lambda selection
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
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.
Upvotes: 0
Views: 1274
Reputation: 16104
I'd suggest to instead of .ToString()
, parse id
to the type userId
is.
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:
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.
Upvotes: 2