HashSet with Index Access

后端 未结 5 1387
轻奢々
轻奢々 2021-01-07 11:58

I would need a data structure that

  1. Allows me to add/item to it
  2. Do not allow duplication
  3. access the collection via index

I am t

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-07 12:48

    You can do it by extending the HashSet, meat of it to see if it contains the element, and thats O(1), reaturn that  element, so no harm done in that case. Here is the derived one:
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    
    namespace Tester
    {
        // Summary:
        //     Represents a set of values.
        //
        // Type parameters:
        //   T:
        //     The type of elements in the hash set.
        [Serializable]
        public class HashSetExt : HashSet
        {
            // Summary:
            //     Initializes a new instance of the System.Collections.Generic.HashSetExt class
            //     that is empty and uses the default equality comparer for the set type.
            public HashSetExt() : base() { }
    
            public HashSetExt(IEnumerable collection) : base(collection) { }
            public HashSetExt(IEqualityComparer comparer) : base(comparer) { }
    
            public HashSetExt(IEnumerable collection, IEqualityComparer comparer) : base(collection, comparer) { }
    
            protected HashSetExt(SerializationInfo info, StreamingContext context) : base(info, context) { }
    
            public T this[T item]
            {
                get
                {
                    if (this.Contains(item))
                    {
                        return item;
                    }
                    throw new KeyNotFoundException();
                }
            }
        }
    }
    

提交回复
热议问题