S M
S M

Reputation: 3233

How to get value of a object member from a dictionary

I have a dictionary

Dictionary<int, UserSession> UserSessionLookupTable

class UserSession 
{ 
    public int SessionId { get; set; } 
    public string UserName { get; set; } 
    public Guid SessionGuid { get; set; } 
    public DateTime LoginTime { get; set; } 
} 

How can I retrive the value sessionGuid with key=1 from dictionary in c#

Upvotes: 0

Views: 499

Answers (1)

Tim Rutter
Tim Rutter

Reputation: 4679

Like this:

var guid = UserSessionLookupTable[1].SessionGuid;

Be aware though that if the key is not present in the dictionary you can get an KeyNotFoundException thrown. To avoid this you could do:

public Guid GetSessionGuid(int key)
{
    UserSession session; 
    return UserSessionLookupTable.TryGetValue(key, out session) ? session.SessionGuid : null;
}

Upvotes: 5

Related Questions