我需要一个包含 2 种不同类型的多个键的字典(int 和 string,都是唯一的,因此它们只能出现在 1 个键中)。举个例子:可以通过GroupdId或者其中一个成员名来查询群组信息(GroupInfo):
GroupId MemberNames GroupInfo
{1, John, Mary, Joe} ==> {GroupInfo}
因此,当 id (1) 或其中一个成员名称 (John) 请求时,应返回群组信息。
我的第一个解决方案是创建一个包含 GroupdId 和 MemberNames 的键,并使用覆盖的 Equals 方法比较 GroupIds 并查找成员列表。但是,要使这些条目相等:
GroupId MemberNames
{0, John}
{1, null}
{1, Mary}
GetHashCode 必须返回相同的常量值。这将导致字典变成链表,并且在最佳情况下性能下降到 O(N) 查找。
另一种解决方案是分别保留 2 个字典:GroupId ==> GroupInfo,MemberName ==> GroupInfo。
还有其他想法吗?
最佳答案
根据您在评论中的描述
how'd you delete by a key? For example given a key "John" all other keys should be deleted as well.
现在您可能已经清楚“词典”不是您要找的东西。主要是因为您需要多种键类型,并且需要将键映射到其他键。
因此您可以创建自己的实现 IDictionary 的类。基本如下。
class MultiKeyDictionary : IDictionary
{
Dictionary<string, GroupInfo> stringDict = new Dictionary<string, GroupInfo>();
Dictionary<int, GroupInfo> intDict = new Dictionary<int, GroupInfo>();
Dictionary<GroupInfo, List<object>> keysDict = new Dictionary<GroupInfo, List<object>>();
//Each of these would add to their own dictionary, as well as adding the backwards
//entry in the "keysDict"
public void Add(string memberName, GroupInfo value);
public void Add(int key, GroupInfo value);
public bool Contains(string key);
public bool Contains(int key);
//This would be the enumerator of the "keys" of "keysDict"
//because it is actually a list of all GroupInfos
public IDictionaryEnumerator GetEnumerator()
public ICollection NameKeys;
public ICollection GroupIDKeys;
//This is to adhere to the interface. It should be carefully commented or even deprecated.
public ICollection Keys;
//For this, you look up the GroupInfo for the key, then do
//foreach(object key in keysDict[<groupInfoIJustLookedUp>]) {
// if(key.gettype == typeof(string) stringDict.Remove(key);
// else if (key.gettype == typeof(int) intDict.Remove(key);
// else //WHAT?!?
//}
public void Remove(string key);
public void Remove(int key);
//This would be the "Keys" collection of the "keysDict"
public ICollection Values;
//etc... etc...
public object this[string memberName];
public object this[int groupId];
}
关于c# - 带有可选键的多键字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198459/