Initializing Lookup

前端 未结 6 1602
轮回少年
轮回少年 2021-01-07 17:47

How do i declare a new lookup class for a property in the object initializer routine in c#?

E.g.

new Component() { ID = 1, Name = \"MOBO\", Category          


        
6条回答
  •  轮回少年
    2021-01-07 18:10

    Here's my attempt on this. Make sure the key is immutable (Gist).

    public class MultiValueDictionary
    : Collection, ILookup
    {
      public MultiValueDictionary(Func keyForItem)
        : base(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, IEnumerable, IList
      {
        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;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
          foreach (var group in base.Items)
            foreach (var item in group)
              yield return item;
        }
    
        const string IndexError = "Indexing not supported.";
        public int IndexOf(TElement item) => throw new NotSupportedException(IndexError);
        public void Insert(int index, TElement item) => Add(item);
        public bool Contains(TElement item) => Items.Contains(item);
        public void CopyTo(TElement[] array, int arrayIndex) =>
        throw new NotSupportedException(IndexError);
        new IEnumerable Items => this;
        public bool IsReadOnly => false;
        TElement IList.this[int index]
        {
          get => throw new NotSupportedException(IndexError);
          set => throw new NotSupportedException(IndexError);
        }
      }
    
      class Grouping : Collection, IGrouping
      {
        public Grouping(TKey key) => Key = key;
        public TKey Key { get; }
      }
    }
    

提交回复
热议问题