.NET基类库中是否有允许使用重复键的字典类?我发现的唯一解决方案是创建一个类,如:

Dictionary<string, List<object>>

但这对实际使用非常恼火。在Java中,我相信MultiMap可以实现这一点,但无法在.NET中找到模拟。

有帮助吗?

解决方案

如果您使用的是.NET 3.5,请使用 Lookup class。

编辑:您通常使用创建Enumerable.ToLookup <=> 。这确实假设您之后不需要更改它 - 但我通常发现它已经足够好了。

如果为你工作,我认为框架中没有任何东西可以提供帮助 - 并且使用字典就像它一样好:(

其他提示

List类实际上非常适用于包含重复项的键/值集合,您希望迭代该集合。例如:

List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();

// add some values to the collection here

for (int i = 0;  i < list.Count;  i++)
{
    Print(list[i].Key, list[i].Value);
}

以下是使用List <!> lt;执行此操作的一种方法。 <!> KeyValuePair LT; string,string <!> gt; GT <!>;

public class ListWithDuplicates : List<KeyValuePair<string, string>>
{
    public void Add(string key, string value)
    {
        var element = new KeyValuePair<string, string>(key, value);
        this.Add(element);
    }
}

var list = new ListWithDuplicates();
list.Add("k1", "v1");
list.Add("k1", "v2");
list.Add("k1", "v3");

foreach(var item in list)
{
    string x = string.format("{0}={1}, ", item.Key, item.Value);
}

输出k1 = v1,k1 = v2,k1 = v3

如果您使用字符串作为键和值,则可以使用 System.Collections.Specialized.NameValueCollection ,它将通过GetValues(字符串键)方法返回一个字符串值数组。

我刚刚看到了 PowerCollections 库,其中包括一个名为MultiDictionary的类。这整齐地包含了这种功能。

关于使用Lookup非常重要的说明:

您可以通过在实现Lookup(TKey, TElement)

的对象上调用ToLookup来创建IEnumerable(T)的实例

没有公共构造函数来创建<=>的新实例。此外,<=>对象是不可变的,也就是说,在创建<=>对象后,您无法添加或删除元素或键。

(来自MSDN)

我认为这对于大多数用途来说都是一个阻碍。

我认为像List<KeyValuePair<object, object>>这样的事情可以做到这一点。

如果您使用<!> gt; = .NET 4,则可以使用Tuple Class:

// declaration
var list = new List<Tuple<string, List<object>>>();

// to add an item to the list
var item = Tuple<string, List<object>>("key", new List<object>);
list.Add(item);

// to iterate
foreach(var i in list)
{
    Console.WriteLine(i.Item1.ToString());
}

查看 C5's HashBag 课程。

很容易<!>“滚动你自己的<!>”;允许<!>“重复键<!>”的字典版本;条目。这是一个简单的粗略实现。您可能需要考虑在IDictionary<T>上添加对大多数(如果不是全部)的支持。

public class MultiMap<TKey,TValue>
{
    private readonly Dictionary<TKey,IList<TValue>> storage;

    public MultiMap()
    {
        storage = new Dictionary<TKey,IList<TValue>>();
    }

    public void Add(TKey key, TValue value)
    {
        if (!storage.ContainsKey(key)) storage.Add(key, new List<TValue>());
        storage[key].Add(value);
    }

    public IEnumerable<TKey> Keys
    {
        get { return storage.Keys; }
    }

    public bool ContainsKey(TKey key)
    {
        return storage.ContainsKey(key);
    }

    public IList<TValue> this[TKey key]
    {
        get
        {
            if (!storage.ContainsKey(key))
                throw new KeyNotFoundException(
                    string.Format(
                        "The given key {0} was not found in the collection.", key));
            return storage[key];
        }
    }
}

关于如何使用它的简单示例:

const string key = "supported_encodings";
var map = new MultiMap<string,Encoding>();
map.Add(key, Encoding.ASCII);
map.Add(key, Encoding.UTF8);
map.Add(key, Encoding.Unicode);

foreach (var existingKey in map.Keys)
{
    var values = map[existingKey];
    Console.WriteLine(string.Join(",", values));
}

回答原来的问题。类似Dictionary<string, List<object>>的东西是在MultiMap中的Code Project类中实现的。

您可以在以下链接中找到更多信息: http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx

NameValueCollection支持一个键下的多个字符串值(也是一个字符串),但它是我所知道的唯一示例。

当我遇到需要这种功能的情况时,我倾向于创建类似于示例中的构造。

使用List<KeyValuePair<string, object>>选项时,可以使用LINQ进行搜索:

List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();
//fill it here
var q = from a in myList Where a.Key.Equals("somevalue") Select a.Value
if(q.Count() > 0){ //you've got your value }

我使用的方式只是一个

Dictionary<string, List<string>>

这样你就有了一个包含字符串列表的键。

示例:

List<string> value = new List<string>();
if (dictionary.Contains(key)) {
     value = dictionary[key];
}
value.Add(newValue);

你的意思是全等而不是真正的重复吗?否则哈希表将无法工作。

Congruent意味着两个单独的键可以散列到等效值,但键不相等。

例如:假设你的哈希表的哈希函数只是hashval = key mod 3. 1和4都映射到1,但它们是不同的值。这就是您对列表的想法发挥作用的地方。

当你需要查找1时,该值被散列为1,遍历列表直到找到Key = 1。

如果允许插入重复键,则无法区分哪些键映射到哪些值。

我偶然发现了这篇文章以寻找相同的答案,但没有找到,所以我使用词典列表来构建一个简单的示例解决方案,覆盖[]运算符以在列表中添加新词典其他人有一个给定的键(set),并返回一个值列表(get)。
这是丑陋和低效的,它只能通过键获取/设置,它总是返回一个列表,但它有效:

 class DKD {
        List<Dictionary<string, string>> dictionaries;
        public DKD(){
            dictionaries = new List<Dictionary<string, string>>();}
        public object this[string key]{
             get{
                string temp;
                List<string> valueList = new List<string>();
                for (int i = 0; i < dictionaries.Count; i++){
                    dictionaries[i].TryGetValue(key, out temp);
                    if (temp == key){
                        valueList.Add(temp);}}
                return valueList;}
            set{
                for (int i = 0; i < dictionaries.Count; i++){
                    if (dictionaries[i].ContainsKey(key)){
                        continue;}
                    else{
                        dictionaries[i].Add(key,(string) value);
                        return;}}
                dictionaries.Add(new Dictionary<string, string>());
                dictionaries.Last()[key] =(string)value;
            }
        }
    }

我将@Hector Correa的答案更改为包含泛型类型的扩展,并为其添加了自定义TryGetValue。

  public static class ListWithDuplicateExtensions
  {
    public static void Add<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
    {
      var element = new KeyValuePair<TKey, TValue>(key, value);
      collection.Add(element);
    }

    public static int TryGetValue<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, out IEnumerable<TValue> values)
    {
      values = collection.Where(pair => pair.Key.Equals(key)).Select(pair => pair.Value);
      return values.Count();
    }
  }

这是一种两种方式并发字典我认为这会对你有所帮助:

public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
    private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
    private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();

    public ICollection<T1> Keys
    {
        get
        {
            return _keyValue.Keys;
        }
    }

    public ICollection<T2> Values
    {
        get
        {
            return _valueKey.Keys;
        }
    }

    public int Count
    {
        get
        {
            return _keyValue.Count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public List<T2> this[T1 index]
    {
        get { return _keyValue[index]; }
        set { _keyValue[index] = value; }
    }

    public List<T1> this[T2 index]
    {
        get { return _valueKey[index]; }
        set { _valueKey[index] = value; }
    }

    public void Add(T1 key, T2 value)
    {
        lock (this)
        {
            if (!_keyValue.TryGetValue(key, out List<T2> result))
                _keyValue.TryAdd(key, new List<T2>() { value });
            else if (!result.Contains(value))
                result.Add(value);

            if (!_valueKey.TryGetValue(value, out List<T1> result2))
                _valueKey.TryAdd(value, new List<T1>() { key });
            else if (!result2.Contains(key))
                result2.Add(key);
        }
    }

    public bool TryGetValues(T1 key, out List<T2> value)
    {
        return _keyValue.TryGetValue(key, out value);
    }

    public bool TryGetKeys(T2 value, out List<T1> key)
    {
        return _valueKey.TryGetValue(value, out key);
    }

    public bool ContainsKey(T1 key)
    {
        return _keyValue.ContainsKey(key);
    }

    public bool ContainsValue(T2 value)
    {
        return _valueKey.ContainsKey(value);
    }

    public void Remove(T1 key)
    {
        lock (this)
        {
            if (_keyValue.TryRemove(key, out List<T2> values))
            {
                foreach (var item in values)
                {
                    var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
                }
            }
        }
    }

    public void Remove(T2 value)
    {
        lock (this)
        {
            if (_valueKey.TryRemove(value, out List<T1> keys))
            {
                foreach (var item in keys)
                {
                    var remove2 = _keyValue.TryRemove(item, out List<T2> values);
                }
            }
        }
    }

    public void Clear()
    {
        _keyValue.Clear();
        _valueKey.Clear();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _keyValue.GetEnumerator();
    }
}

的示例:

public class TestA
{
    public int MyProperty { get; set; }
}

public class TestB
{
    public int MyProperty { get; set; }
}

            HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();

            var a = new TestA() { MyProperty = 9999 };
            var b = new TestB() { MyProperty = 60 };
            var b2 = new TestB() { MyProperty = 5 };
            hashMapDictionary.Add(a, b);
            hashMapDictionary.Add(a, b2);
            hashMapDictionary.TryGetValues(a, out List<TestB> result);
            foreach (var item in result)
            {
                //do something
            }

我使用这个简单的类:

public class ListMap<T,V> : List<KeyValuePair<T, V>>
{
    public void Add(T key, V value) {
        Add(new KeyValuePair<T, V>(key, value));
    }

    public List<V> Get(T key) {
        return FindAll(p => p.Key.Equals(key)).ConvertAll(p=> p.Value);
    }
}

用法:

var fruits = new ListMap<int, string>();
fruits.Add(1, "apple");
fruits.Add(1, "orange");
var c = fruits.Get(1).Count; //c = 2;

您可以定义构建复合字符串键的方法 你想在哪里使用字典你必须使用这种方法来建立你的密钥 例如:

private string keyBuilder(int key1, int key2)
{
    return string.Format("{0}/{1}", key1, key2);
}

使用:

myDict.ContainsKey(keyBuilder(key1, key2))

重复键会破坏整个字典的合约。在字典中,每个键都是唯一的,并映射到单个值。如果要将对象链接到任意数量的其他对象,最好的选择可能类似于DataSet(通常用于表格)。将您的密钥放在一列中,将值放在另一列中。这明显慢于字典,但这是你失去散列关键对象能力的权衡。

这也是可能的:

Dictionary<string, string[]> previousAnswers = null;

这样,我们可以拥有唯一的密钥。希望这对你有用。

您可以使用不同的大小写添加相同的键,例如:

KEY1,点击 key1的结果 KEY1结果 KEY1结果 KEY1结果 KEY1结果

我知道这是虚假答案,但对我有用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top