Remove Duplicates from IList by function - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Remove Duplicates from IList by function

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static List<TSource> RemoveDuplicates<TSource, TCheck>(this IList<TSource> values, Func<TSource, TCheck> dupliCheck)
        {//  ww  w  .  ja  v a 2s  . c  om
            var duplicateCheck = new HashSet<TCheck>();
            var res = new List<TSource>(values.Count);

            foreach (var value in values)
            {
                var val = dupliCheck(value);

                if (duplicateCheck.Contains(val))
                    continue;

                duplicateCheck.Add(val);
                res.Add(value);
            }

            return res;
        }
        public static List<TSource> RemoveDuplicates<TSource>(this IList<TSource> values)
        {
            var res = new List<TSource>(values.Count);
            var duplicateCheck = new HashSet<TSource>();
            
            foreach (var value in values)
            {
                if (duplicateCheck.Contains(value))
                    continue;

                duplicateCheck.Add(value);
                res.Add(value);
            }

            return res;
        }
        public static bool Contains<T>(this IEnumerable<T> me, Predicate<T> condition)
        {
            foreach (var val in me)
            {
                if (condition(val)) 
                    return true;
            }
            return false;
        }
}

Related Tutorials