Multi Value Dictionary?

后端 未结 10 1875
萌比男神i
萌比男神i 2020-11-27 20:45

Anyone know of a good implementation of a MultiValueDictionary? Basically, I want something that allows multiple values per key. I want to be able to do somethi

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 21:33

    Yet here's my attempt using ILookup and an internal KeyedCollection. Make sure the key property is immutable.
    Cross posted here.

    public class Lookup : Collection, ILookup
    {
      public Lookup(Func keyForItem)
        : base((IList)new Collection(keyForItem))
      {
      }
    
      new Collection Items => (Collection)base.Items;
    
      public IEnumerable this[TKey key] => Items[key];
      public bool Contains(TKey key) => Items.Contains(key);
      IEnumerator>
        IEnumerable>.GetEnumerator() => Items.GetEnumerator();
    
      class Collection : KeyedCollection
      {
        Func KeyForItem { get; }      
        public Collection(Func keyForItem) => KeyForItem = keyForItem;
        protected override TKey GetKeyForItem(Grouping item) => item.Key;
    
        public void Add(TElement item)
        {
          var key = KeyForItem(item);
          if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
            collection.Add(item);
          else
            Add(new Grouping(key) { item });
        }
    
        public bool Remove(TElement item)
        {
          var key = KeyForItem(item);
          if (Dictionary != null && Dictionary.TryGetValue(key, out var collection)
            && collection.Remove(item))
          {
            if (collection.Count == 0)
              Remove(key);
            return true;
          }
          return false;
        }
    
      }
      class Grouping : Collection, IGrouping
      {
        public Grouping(TKey key) => Key = key;
        public TKey Key { get; }
      }
    }
    

提交回复
热议问题