c# - 带有可选键的多键字典

标签 c# .net-3.5 dictionary hashtable

我需要一个包含 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/

相关文章:

c# - Rx 扩展 : Where is Parallel. ForEach?

c# - 从 Windows 服务打印 EMF

c - 如何用c实现单词拼写检查?

c# - 在独立的应用程序中运行迁移

c# - 如何将文本保留在控制台顶部?

javascript - 如何在 Breeze 中对扩展实体使用谓词

c# - 定义不指定参数的抽象方法

c# - 我可以让我的程序集引用另一个程序集的任何版本吗?

c# - 将类列表添加到字典 C#

python - 字典 - 用 _ 替换键的空格,保持值相同