/// <summary> /// Implementation Notes: /// Since resizes are relatively expensive (require rehashing), this attempts to minimize /// the need to resize by setting the initial capacity based on size of collection. /// </summary> /// <param name="collection"></param> /// <param name="comparer"></param> public HashSet(IEnumerable <T> collection, IEqualityComparer <T> comparer) : this(comparer) { if (collection == null) { throw new ArgumentNullException("collection"); } // to avoid excess resizes, first set size based on collection's count. Collection // may contain duplicates, so call TrimExcess if resulting hashset is larger than // threshold int suggestedCapacity = 0; ICollection <T> coll = collection as ICollection <T>; if (coll != null) { suggestedCapacity = coll.Count; } Initialize(suggestedCapacity); this.UnionWith(collection); if ((m_count == 0 && m_slots.Length > HashHelpers.GetMinPrime()) || (m_count > 0 && m_slots.Length / m_count > ShrinkThreshold)) { TrimExcess(); } }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Collections.Generic.HashSet`1" /> class that uses the specified equality comparer for the set type, /// contains elements copied from the specified collection, /// and has sufficient capacity to accommodate the number of elements copied. /// </summary> /// <param name="collection">The collection whose elements are copied to the new set.</param> /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1" /> implementation to use when comparing values in the set, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1" /> implementation for the set type.</param> /// <exception cref="T:System.ArgumentNullException">collection is null.</exception> public HashSet(IEnumerable <T> collection, IEqualityComparer <T> comparer) : this(comparer) { if (collection == null) { throw new ArgumentNullException("collection"); } int capacity = 0; ICollection <T> is2 = collection as ICollection <T>; if (is2 != null) { capacity = is2.Count; } this.Initialize(capacity); this.UnionWith(collection); if (((this.m_count == 0) && (this.m_slots.Length > HashHelpers.GetMinPrime())) || ((this.m_count > 0) && ((this.m_slots.Length / this.m_count) > 3))) { this.TrimExcess(); } }
public HashSet(IEnumerable <T> collection, IEqualityComparer <T> comparer) : this(comparer) { if (collection == null) { throw new ArgumentNullException("collection"); } int suggestedCapacity = 0; ICollection <T> coll = collection as ICollection <T>; if (coll != null) { suggestedCapacity = coll.Count; } Initialize(suggestedCapacity); this.UnionWith(collection); if ((_count == 0 && _slots.Length > HashHelpers.GetMinPrime()) || (_count > 0 && _slots.Length / _count > ShrinkThreshold)) { TrimExcess(); } }