278

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

Dictionary<string, List<object>>

但这对于实际使用来说是相当烦人的。在 Java 中,我相信 MultiMap 可以做到这一点,但在 .NET 中找不到类似物。

4

24 回答 24

236

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

编辑:您通常创建一个Lookupusing Enumerable.ToLookup. 这确实假设您之后不需要更改它 - 但我通常发现这已经足够了。

如果这对您不起作用,我认为框架中没有任何帮助 - 并且使用字典尽可能好:(

于 2008-09-28T16:46:37.970 回答
185

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);
}
于 2009-05-08T21:02:55.110 回答
43

这是使用 List< KeyValuePair< string, string >> 执行此操作的一种方法

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

于 2012-03-23T18:14:14.540 回答
25

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

于 2008-09-28T16:39:02.747 回答
19

我刚刚遇到了PowerCollections库,其中包括一个名为 MultiDictionary 的类。这巧妙地包装了这种类型的功能。

于 2008-09-28T16:39:45.350 回答
14

我认为类似的事情List<KeyValuePair<object, object>>会完成这项工作。

于 2008-09-28T16:37:47.240 回答
14

关于使用 Lookup 的非常重要的注意事项:

Lookup(TKey, TElement)您可以通过调用ToLookup实现的对象来创建 a 的实例IEnumerable(T)

没有公共构造函数来创建 a 的新实例Lookup(TKey, TElement)。此外,Lookup(TKey, TElement)对象是不可变的,也就是说,您不能在Lookup(TKey, TElement)对象创建后添加或删除元素或键。

(来自 MSDN)

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

于 2008-09-28T20:24:24.327 回答
11

如果您使用 >= .NET 4,那么您可以使用TupleClass:

// 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());
}
于 2012-08-17T05:52:21.900 回答
8

“滚动你自己的”版本的字典很容易,它允许“重复键”条目。这是一个粗略的简单实现。您可能需要考虑在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));
}
于 2016-04-07T03:47:13.887 回答
7

由于新的 C#(我相信它来自 7.0),您还可以执行以下操作:

var duplicatedDictionaryExample = new List<(string Key, string Value)> { ("", "") ... }

并且您将它用作标准列表,但有两个值命名为您想要的任何值

foreach(var entry in duplicatedDictionaryExample)
{ 
    // do something with the values
    entry.Key;
    entry.Value;
}
于 2019-11-26T16:50:26.593 回答
4

在回答原始问题。类似的东西Dictionary<string, List<object>>是在一个名为MultiMapThe 的类中实现的Code Project

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

于 2010-05-28T13:00:43.623 回答
3

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

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

于 2008-09-28T16:41:35.813 回答
3

使用该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 }
于 2011-07-19T15:37:23.183 回答
2

你的意思是一致的,而不是实际的重复?否则哈希表将无法工作。

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

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

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

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

于 2008-09-28T16:38:58.953 回答
2

我使用的方式只是一个

Dictionary<string, List<string>>

这样,您就有一个保存字符串列表的键。

例子:

List<string> value = new List<string>();
if (dictionary.Contains(key)) {
     value = dictionary[key];
}
value.Add(newValue);
于 2012-04-07T17:59:52.160 回答
2

您可以创建自己的字典包装器,就像这样,作为奖励,它支持空值作为键:

/// <summary>
/// Dictionary which supports duplicates and null entries
/// </summary>
/// <typeparam name="TKey">Type of key</typeparam>
/// <typeparam name="TValue">Type of items</typeparam>
public class OpenDictionary<TKey, TValue>
{
    private readonly Lazy<List<TValue>> _nullStorage = new Lazy<List<TValue>>(
        () => new List<TValue>());

    private readonly Dictionary<TKey, List<TValue>> _innerDictionary =
        new Dictionary<TKey, List<TValue>>();

    /// <summary>
    /// Get all entries
    /// </summary>
    public IEnumerable<TValue> Values =>
        _innerDictionary.Values
            .SelectMany(x => x)
            .Concat(_nullStorage.Value);

    /// <summary>
    /// Add an item
    /// </summary>
    public OpenDictionary<TKey, TValue> Add(TKey key, TValue item)
    {
        if (ReferenceEquals(key, null))
            _nullStorage.Value.Add(item);
        else
        {
            if (!_innerDictionary.ContainsKey(key))
                _innerDictionary.Add(key, new List<TValue>());

            _innerDictionary[key].Add(item);
        }

        return this;
    }

    /// <summary>
    /// Remove an entry by key
    /// </summary>
    public OpenDictionary<TKey, TValue> RemoveEntryByKey(TKey key, TValue entry)
    {
        if (ReferenceEquals(key, null))
        {
            int targetIdx = _nullStorage.Value.FindIndex(x => x.Equals(entry));
            if (targetIdx < 0)
                return this;

            _nullStorage.Value.RemoveAt(targetIdx);
        }
        else
        {
            if (!_innerDictionary.ContainsKey(key))
                return this;

            List<TValue> targetChain = _innerDictionary[key];
            if (targetChain.Count == 0)
                return this;

            int targetIdx = targetChain.FindIndex(x => x.Equals(entry));
            if (targetIdx < 0)
                return this;

            targetChain.RemoveAt(targetIdx);
        }

        return this;
    }

    /// <summary>
    /// Remove all entries by key
    /// </summary>
    public OpenDictionary<TKey, TValue> RemoveAllEntriesByKey(TKey key)
    {
        if (ReferenceEquals(key, null))
        {
            if (_nullStorage.IsValueCreated)
                _nullStorage.Value.Clear();
        }       
        else
        {
            if (_innerDictionary.ContainsKey(key))
                _innerDictionary[key].Clear();
        }

        return this;
    }

    /// <summary>
    /// Try get entries by key
    /// </summary>
    public bool TryGetEntries(TKey key, out IReadOnlyList<TValue> entries)
    {
        entries = null;

        if (ReferenceEquals(key, null))
        {
            if (_nullStorage.IsValueCreated)
            {
                entries = _nullStorage.Value;
                return true;
            }
            else return false;
        }
        else
        {
            if (_innerDictionary.ContainsKey(key))
            {
                entries = _innerDictionary[key];
                return true;
            }
            else return false;
        }
    }
}

使用示例:

var dictionary = new OpenDictionary<string, int>();
dictionary.Add("1", 1); 
// The next line won't throw an exception; 
dictionary.Add("1", 2);

dictionary.TryGetEntries("1", out List<int> result); 
// result is { 1, 2 }

dictionary.Add(null, 42);
dictionary.Add(null, 24);
dictionary.TryGetEntries(null, out List<int> result); 
// result is { 42, 24 }
于 2019-10-26T14:51:36.017 回答
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;
            }
        }
    }
于 2011-05-23T16:11:43.410 回答
1

我将 @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();
    }
  }
于 2018-04-30T17:50:01.653 回答
0

这是一种双向并发字典,我认为这会对您有所帮助:

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
            }
于 2017-11-28T10:18:11.817 回答
0

我使用这个简单的类:

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;
于 2019-05-17T11:25:36.833 回答
-1

您可以定义一种方法来构建复合字符串键,每个您想使用字典的地方都必须使用此方法来构建您的键,例如:

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

使用:

myDict.ContainsKey(keyBuilder(key1, key2))
于 2015-05-25T12:50:11.767 回答
-3

重复的键会破坏 Dictionary 的整个合同。在字典中,每个键都是唯一的并映射到单个值。如果您想将一个对象链接到任意数量的其他对象,最好的选择可能是类似于 DataSet 的东西(通常的说法是表)。将您的键放在一列中,将您的值放在另一列中。这比字典慢得多,但这是您失去散列关键对象能力的权衡。

于 2008-09-28T16:38:09.253 回答
-4

这也是可能的:

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

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

于 2015-04-19T21:19:39.577 回答
-11

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

键1
键1
键1 键 1

1 键
1

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

于 2015-01-15T23:07:15.317 回答