.NET 字典中的重复键

本文关键字:字典 NET | 更新日期: 2023-09-27 17:47:21

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

Dictionary<string, List<object>>

但这实际使用起来很烦人。 在Java中,我相信MultiMap可以做到这一点,但在.NET中找不到类似物。

.NET 字典中的重复键

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

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

如果这对你不起作用,我认为框架中没有任何帮助 - 使用字典就像它得到的一样好:(

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<字符串,字符串>>执行此操作的一种方法

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的类。 这巧妙地包装了这种类型的功能。

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

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

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

(来自MSDN)

我认为这将是大多数用途的障碍。

由于新的 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;
}
我认为

List<KeyValuePair<object, object>>这样的东西可以完成这项工作。

如果您使用的是>= .NET 4,则可以使用 Tuple 类:

// 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());
}
"

滚动自己的"字典版本很容易,允许"重复键"条目。这是一个粗略的简单实现。您可能需要考虑在 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>> 这样的东西是在 Code Project 中名为 MultiMap 的类中实现的。

您可以在以下链接中找到更多信息: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 }

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

全等意味着两个单独的键可以哈希为等效值,但键不相等。

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

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

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

我使用的方式只是一个

Dictionary<string, List<string>>

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

例:

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

您可以创建自己的字典包装器,如下所示,作为奖励,它支持空值作为键:

/// <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 }

我偶然发现了这篇文章以寻找相同的答案,但没有找到,所以我使用字典列表安装了一个基本的示例解决方案,覆盖 [] 运算符以在所有其他字典都有给定键(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;
            }
        }
    }

我将 Correa 的答案@Hector更改为具有泛型类型的扩展,并向其添加了自定义的 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;

重复的键会破坏字典的整个合约。在字典中,每个键都是唯一的,并映射到单个值。如果要将一个对象链接到任意数量的附加对象,最好的办法可能是类似于数据集(通俗地说是表)的东西。将键放在一列中,将值放在另一列中。这比字典慢得多,但这是您失去对键对象进行哈希处理的能力的权衡。

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

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

用于使用:

myDict.ContainsKey(keyBuilder(key1, key2))

这也是可能的:

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

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

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

key1
键1
键1KeY1
kEy1
keY1

我知道是愚蠢的答案,但对我有用。