Generic Set : Set « Collections Data Structure « C# / C Sharp






Generic Set

 
//http://tfsbugger.codeplex.com/
//GNU General Public License version 2 (GPLv2)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace TfsBugger.Util
{
    public class Set<T> : Collection<T>
        where T : IComparable
    {
        #region Ctors
        public Set()
        {

        }


        public Set(IList<T> list)
        {
            foreach (T t in list)
                Add(t);
        }


        public Set(IEnumerable<T> items)
        {
            AddRange(items);
        }


        public Set(params T[] items)
        {
            AddRange(items);
        }
        #endregion


        public void AddRange(IEnumerable<T> items)
        {
            foreach (T t in items)
                Add(t);
        }


        public bool RemoveIfPresent(T item)
        {
            if (Contains(item))
            {
                Remove(item);
                return true;
            }

            return false;
        }


        public void Sort(Comparison<T> comparison)
        {
            IEnumerable<T> items = from i in this
                                   orderby comparison
                                   select i;

            Clear();
            AddRange(items);
        }


        public bool TryAdd(T item)
        {
            if (!this.Contains(item))
            {
                Add(item);
                return true;
            }

            return false;
        }


        public bool TryRemove(T item)
        {
            if (this.Contains(item))
            {
                Remove(item);
                return true;
            }

            return false;
        }


        protected override void InsertItem(int index, T item)
        {
            if (!this.Contains(item))
                base.InsertItem(index, item);
        }


        public void ForEach(Action<T> action)
        {
            foreach (T item in this)
                action(item);
        }


        public T[] ToArray()
        {
            return new List<T>(this).ToArray();
        }
    }
}

   
  








Related examples in the same category

1.Put the Set class into its own namespacePut the Set class into its own namespace
2.Hash Set
3.Hash Set 2