Collection that allows only unique items in .NET?

后端 未结 7 2469
天涯浪人
天涯浪人 2020-12-13 16:35

Is there a collection in C# that will not let you add duplicate items to it? For example, with the silly class of

public class Customer {
    public string F         


        
7条回答
  •  轮回少年
    2020-12-13 17:08

    Just to add my 2 cents...

    if you need a ValueExistingException-throwing HashSet you can also create your collection easily:

    public class ThrowingHashSet : ICollection
    {
        private HashSet innerHash = new HashSet();
    
        public void Add(T item)
        {
            if (!innerHash.Add(item))
                throw new ValueExistingException();
        }
    
        public void Clear()
        {
            innerHash.Clear();
        }
    
        public bool Contains(T item)
        {
            return innerHash.Contains(item);
        }
    
        public void CopyTo(T[] array, int arrayIndex)
        {
            innerHash.CopyTo(array, arrayIndex);
        }
    
        public int Count
        {
            get { return innerHash.Count; }
        }
    
        public bool IsReadOnly
        {
            get { return false; }
        }
    
        public bool Remove(T item)
        {
            return innerHash.Remove(item);
        }
    
        public IEnumerator GetEnumerator()
        {
            return innerHash.GetEnumerator();
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
    

    this can be useful for example if you need it in many places...

提交回复
热议问题