0

I'm just looking at SignalR Chat application and I'm not sure what the following line mean?

Especially the " x => " part.

var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ;

And then it checks the variable and sends message.

if (toUser != null && fromUser!=null)
{
    "Send Message"
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
SpiderWeb
  • 79
  • 6

2 Answers2

3

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.

Community
  • 1
  • 1
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0
var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ;

returns the first user which have its ConnectionId property equals to the value in your "toUserId" variable, and puts it in toUser. If there is no matching user, toUserId will be equal to null.

Read http://msdn.microsoft.com/en-us/library/vstudio/bb340482%28v=vs.90%29.aspx for more details

Concerning

if (toUser != null && fromUser!=null) { "Send Message" }

I find it so simple that I can't even know what to answer. If you're not able to read it, I'm sorry but you're on the wrong website. As you provide it, it doesn't do anything to speak frankly : it will not compile. So please post a real question

AFract
  • 8,868
  • 6
  • 48
  • 70