Add to ICollection If Not Present - CSharp System.Collections

CSharp examples for System.Collections:ICollection

Description

Add to ICollection If Not Present

Demo Code


using System;//w  w  w  . ja v a 2s.com
using System.Linq;
using System.Collections.Generic;

public class Main{
    public static void AddIfNotPresent<T> (ref ICollection<T> collection, T element)
      {
         AddIfNotPresent (ref collection, element, (o1, o2) => !Check.NullSafeEquals (o1, o2));
      }
    public static void AddIfNotPresent<T> (ref ICollection<T> collection, T element, Func<T, T, bool> containsPreticate)
      {
         collection = collection ?? new List<T> ();
         if (collection.All (p => !containsPreticate (p, element)))
            collection.Add (element);
      }
}

Related Tutorials