3

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.

Joey Morani
  • 25,431
  • 32
  • 84
  • 131

4 Answers4

1

Does anything stop you from using standard Linq FirstOrDefault() method like so:

var item = OnlineUsers.FirstOrDefault(kvp => kvp.Key.Context == myContext);
Charles Prakash Dasari
  • 4,964
  • 1
  • 27
  • 46
  • Well, you're doing a linear search on the dictionary, which more or less defeats the purpose of using a dictionary (although I don't think there's any choice without a redesign. – Servy Sep 21 '12 at 19:34
  • Well, the answer was assuming that the OP wanted a User object as the key for some other purpose and wanted to find out how to search for a value when he had just the context alone and not the whole object. But yes, you are right, if it can be redesigned, then it is the right thing to do. – Charles Prakash Dasari Sep 21 '12 at 19:42
  • As the problem is stated, I don't think there is an answer that will be better than linear. The Dictionary is keyed on User, not Context. – hatchet - done with SOverflow Sep 21 '12 at 19:57
1

How obout something like

var ou = OnlineUsers.First(x => x.Key.Context == "TADA");
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
0

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

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");
Artless
  • 4,522
  • 1
  • 25
  • 40