user3290224
user3290224

Reputation: 77

C# get Dictionary class value

I have small problem with Dictionary.

Here is little bit code:

string user = UserList
  .Where(p => p.Key == im.SenderConnection.RemoteUniqueIdentifier)
  .Select(p => p.Value.Username)
  .ToString();
Console.WriteLine(user);

public class User
{
        public string Username;
}

And that writes to console:

System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.Int64,ChatServer.User],System.String]

Upvotes: 0

Views: 85

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65069

Because you're calling ToString on the result of a Select.

Select is a projection.. and as such, it still returns a collection. You should call FirstOrDefault and retrieve the name:

string user = UserList
    .Where(p => p.Key == im.SenderConnection.RemoteUniqueIdentifier)
    .Select(p => p.Value.Username)
    .First();

Console.WriteLine(user);

Or shorter:

string user = UserList
    .First(p => p.Key == im.SenderConnection.RemoteUniqueIdentifier)
    .Value.Username;

Upvotes: 2

Tilak
Tilak

Reputation: 30698

Try this

string user = UserList.Where(p => p.Key == im.SenderConnection.RemoteUniqueIdentifier).Select(p => p.Value.Username).FirstOrDefault().ToString();

You are Selecting filtered UserList, and not a particular user. Add your Filter to FirstOrDefault to get specific user.

Upvotes: 1

Related Questions