x => x.ConnectionId == toUserId
is a lambda expression. This is a very concise way of declaring an anonymous delegate or method. You could write this instead:
private bool SelectUser(User x)
{
return x.ConnectionId == toUserId; // Where toUserId has to be a field.
}
with this declaration you can write:
User toUser = ConnectedUsers.FirstOrDefault(SelectUser);
Note that there are no braces ()
after SelectUser
, since we don't want to call the method here; we pass it as a delegate. Think of it as a kind of method pointer.
Note also that C# automatically catches the variable toUserId
in the lambda expression and makes it visible to the lambda expression as a field. This is called a closure.
The extension method FirstOrDefault
returns the first user from the ConnectedUsers
enumeration whose connection id matches, or null
if no such user is found (therefore the following if (toUser != null ...)
check.