Getting a value from a ConcurrentDictionary
-
03-07-2021 - |
Question
If I have this ConcurrentDictionary:
public class User
{
public string Context { get; set; }
public bool Owner { get; set; }
}
protected static ConcurrentDictionary<User, string> OnlineUsers = new ConcurrentDictionary<User, string>();
Does anyone know how I would get the value of Owner
if I already have the value of the Context
? Basically I want to do a "find" using the Context
. Thanks.
Solution
It sounds like you need a Dictionary<string, User>
which, when given the context as a string
will tell you which User
it corresponds to. If you are going to need to perform this lookup several times, and there isn't a problem using the additional memory, it may be worth creating such a dictionary.
If you are only going to be doing the search once or twice, or the mappings will be changing so often that you can't keep the dictionary up to date, then you can simply do a linear search on the dictionary using a foreach
loop, or using a LINQ method such as First
or Where
, as demonstrated in other answers.
OTHER TIPS
Does anything stop you from using standard Linq FirstOrDefault()
method like so:
var item = OnlineUsers.FirstOrDefault(kvp => kvp.Key.Context == myContext);
How obout something like
var ou = OnlineUsers.First(x => x.Key.Context == "TADA");
Here you go:
ConcurrentDictionary<User, string> dict = new ConcurrentDictionary<User, string>();
dict.TryAdd(new User() { Context = "a", Ownder = false }, "aa");
dict.TryAdd(new User() { Context = "b", Ownder = false }, "bb");
dict.TryAdd(new User() { Context = "c", Ownder = true }, "cc");
dict.TryAdd(new User() { Context = "d", Ownder = false }, "dd");
IEnumerable<User> list = dict.Keys.Where(p => p.Context == "a");