Contains Duplicates in IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Contains Duplicates in IEnumerable

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/* w  w  w  .  j  a  v  a  2 s.  co  m*/

public class Main{
        public static bool ContainsDuplicates<T>(this IEnumerable<T> self,Func<T,object> pred = null)
        {
            if (pred == null)
                pred = x => x.ToString();
            var sorted = self.OrderBy(pred);
            T last = sorted.FirstOrDefault();
            foreach (var item in sorted.Skip(1))
            {
                if (item.Equals(last))
                {
                    return true;
                }
                last = item;
            }
            return false;
        }
}

Related Tutorials