0

我的字典键是另一个字典。例如,如果我的字典(“游戏”)包含键“我的名字”,我如何查看?我有这样的事情:

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);
     }
}
4

6 回答 6

3

这是行不通的:两个相同组成的字典不会相互比较(链接到 ideone)。

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

一般来说,您不应该在任何可变的内容上键入您的字典。制作一个将字典转换为“规范string表示”的方法,并将其用作字典中string的键。

于 2012-11-30T11:33:07.873 回答
1
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;
}

但是,我不确定这是否是个好主意,密钥应该是不可变的,而 Dictionary 不是不可变的。

于 2012-11-30T11:32:30.717 回答
1

我假设你想要一个层次结构

Games
    ChatRooms

根据实际要求,您可能希望将实际聊天室存储在一个字典中,并将每个游戏的聊天室“索引”存储在另一个字典中。访问实际聊天变成了两步过程:

  1. 从 _chatRoomsPerGame 字典中获取每个游戏的聊天室列表
  2. 从 _allChatRooms 字典中获取实际聊天室。

虽然可以创建自己的对象来托管字典并覆盖 GetHashKey 以使用其他字典的键创建字典,但我怀疑这是否是您真正想要的。

于 2012-11-30T11:53:58.950 回答
0
games.Keys.SelectMany(x => x.Keys).Contains("myname")
于 2012-11-30T11:32:08.120 回答
0

这样的事情可能是:

如果我们有:

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

在某些功能中

public IEnumerable<T> GetByName(string myName) {
    return games.Keys.Where(x=>x.Contains("myName"));
}
于 2012-11-30T11:32:28.347 回答
0

试试这个

 var innerDictionary = rooms.Keys.Where(innerdict => innerdict.ContainsKey(roomName)));
于 2012-11-30T11:32:38.667 回答