Monday, January 09, 2012

Add Item to collection if item not exist

Tnx to Miroslav

So, this is extension methods that enables you to add item in collection if item does not exist already


 public static class CollectionsExtensions
    {
        /// 
        /// Adds item to collection if not exist already.
        /// 
        /// The type of the source.
        /// 
The collection.
        /// 
The element.
        /// 
The comparer.
        /// true if item is added to collection.
        public static bool AddIfNotExist(this ICollection collection, TSource element, Func comparer)
        {
            if (collection == null)
            {
                return false;
            }

            if (collection.Any(comparer))
            {
                return false;
            }
            else
            {
                collection.Add(element);
                return true;
            }
        }

        /// 
        /// Adds item to collection if not exist already.
        /// 
        /// The type of the source.
        /// 
The collection.
        /// 
The element.
        /// true if item is added to collection
        public static bool AddIfNotExist(this ICollection collection, TSource element)
        {
            if (collection == null)
            {
                return false;
            }

            if (collection.Contains(element))
            {
                return false;
            }
            else
            {
                collection.Add(element);
                return true;
            }
        }
    }