Add Distinct to IList - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Add Distinct to IList

Demo Code

// Permission is hereby granted, free of charge, to any person
using System.Globalization;
using System.Linq;
using System.Collections;
using System.Text;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;/*ww  w. j a va  2s. c o  m*/

public class Main{
    public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer)
    {
      if (list.ContainsValue(value, comparer))
        return false;

      list.Add(value);
      return true;
    }
    public static bool AddDistinct<T>(this IList<T> list, T value)
    {
      return list.AddDistinct(value, EqualityComparer<T>.Default);
    }
        // this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T>
    public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
    {
      if (comparer == null)
        comparer = EqualityComparer<TSource>.Default;

      if (source == null)
        throw new ArgumentNullException("source");

      foreach (TSource local in source)
      {
        if (comparer.Equals(local, value))
          return true;
      }

      return false;
    }
}

Related Tutorials