Hashtable with multiple values for single key

后端 未结 11 1776
渐次进展
渐次进展 2021-02-13 13:36

I want to store multiple values in single key like:

HashTable obj = new HashTable();
obj.Add(\"1\", \"test\");
obj.Add(\"1\", \"Test1\");

Right

11条回答
  •  天命终不由人
    2021-02-13 14:04

    I'm using my own MultiDictionary class. It's based on a Dictionary> but offers a bit of syntax sugar on top of that. Should be easy to extent Entry to implement IList

    public class MultiDictionary
    {
        private Dictionary> data = new Dictionary>();
    
        public struct Entry : IEnumerable
        {
            private readonly MultiDictionary mDictionary;
            private readonly TKey mKey;
    
            public TKey Key { get { return mKey; } }
    
            public bool IsEmpty
            {
                get
                {
                    return !mDictionary.data.ContainsKey(Key);
                }
            }
    
            public void Add(TValue value)
            {
                List list;
                if (!mDictionary.data.TryGetValue(Key, out list))
                    list = new List();
                list.Add(value);
                mDictionary.data[Key] = list;
            }
    
            public bool Remove(TValue value)
            {
                List list;
                if (!mDictionary.data.TryGetValue(Key, out list))
                    return false;
                bool result = list.Remove(value);
                if (list.Count == 0)
                    mDictionary.data.Remove(Key);
                return result;
            }
    
            public void Clear()
            {
                mDictionary.data.Remove(Key);
            }
    
            internal Entry(MultiDictionary dictionary, TKey key)
            {
                mDictionary = dictionary;
                mKey = key;
            }
    
            public IEnumerator GetEnumerator()
            {
                List list;
                if (!mDictionary.data.TryGetValue(Key, out list))
                    return Enumerable.Empty().GetEnumerator();
                else
                    return list.GetEnumerator();
            }
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }
    
        public Entry this[TKey key]
        {
            get
            {
                return new Entry(this, key);
            }
        }
    }
    

提交回复
热议问题