Tarida George
Tarida George

Reputation: 1303

C# dictionary key as dictionary

My dictionary key is another dictionary.How can I view if my dictonary("games") ContainsKey "myname" for example ? I have something like this :

Dictionary<string,List<ChatClient>> rooms = new Dictionary<string, List<ChatClient>>();
Dictionary<Dictionary<string, List<ChatClient>>, IGame> games = new Dictionary<Dictionary<string, List<ChatClient>>, IGame>();

public void CreateAGame(string roomName, IGame game) {
     if (rooms.ContainsKey(roomName)) {
         games.Add(rooms, game);
     }
}

Upvotes: 0

Views: 341

Answers (6)

b0rg
b0rg

Reputation: 1897

I assume you want a hierarchy of

Games
    ChatRooms

Depending on actual requirements you'd probably want to store actual chat rooms in one dictionary, and "index" of chat rooms per games in another dictionary. Accessing the actual chat becomes 2 step process:

  1. Get List of Chat Rooms per game from _chatRoomsPerGame dictionary
  2. Get the Actual Chat Room from _allChatRooms dictionary.

While it is possible to create your own object to host a dictionary and override GetHashKey to create a dictionary with a key of other dictionary, I doubt that is what you really want.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is not going to work: two identically composed dictionaries will not compare as equal to each other (link to ideone).

var a = new Dictionary<string,string> {{"a","a"}};
var b = new Dictionary<string,string> {{"a","a"}};
Console.WriteLine(a.Equals(b));

In general, you should not key your dictionary on anything mutable. Make a method that converts a dictionary to a "canonical string representation", and use that string as a key in your dictionary.

Upvotes: 3

Tilak
Tilak

Reputation: 30688

Try this

 var innerDictionary = rooms.Keys.Where(innerdict => innerdict.ContainsKey(roomName)));

Upvotes: 0

nothrow
nothrow

Reputation: 16168

public void ContainsDictKey(Dictionary<Dictionary<string, List<ChatClient>>, IGame> games, string key)
{
    foreach(var l in games)
    {
        if(l.Key.ContainsKey(key))
            return true;
    }
    return false;
}

However, I'm not sure if this is good idea, the key should be immutable, whereas Dictionary isn't immutable.

Upvotes: 1

Tigran
Tigran

Reputation: 62248

Something like this may be:

If we have:

 Dictionary<Dictionary<string, List<ChatClient>>, IGame> games = 
               new Dictionary<Dictionary<string, List<ChatClient>>, IGame>();

and in some function

public IEnumerable<T> GetByName(string myName) {
    return games.Keys.Where(x=>x.Contains("myName"));
}

Upvotes: 0

Dima
Dima

Reputation: 6741

games.Keys.SelectMany(x => x.Keys).Contains("myname")

Upvotes: 0

Related Questions