Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check IEnumerable<T> for items having duplicate properties

How to check if an IEnumerable has two or more items with the same property value ?

For example a class

public class Item
{
    public int Prop1 {get;set;}
    public string Prop2 {get;set;}
}

and then a collection of type IEnumerable<Item>

I need to return false if there are items with duplicate values in Prop1.

like image 887
user137348 Avatar asked Jan 04 '11 19:01

user137348


2 Answers

You want to check only for Prop1 right ?

What about:

IEnumerable<Item> items = ...
var noDistinct = items.GroupBy(x => x.Prop1).All(x => x.Count() == 1);
// it returns true if all items have different Prop1, false otherwise
like image 108
digEmAll Avatar answered Sep 28 '22 19:09

digEmAll


I think this method will work.

public static bool ContainsDuplicates<T1>(this IEnumerable<T1> source, Func<T1, T2> selector)
{
    var d = new HashSet<T2>();
    foreach(var t in source)
    {
        if(!d.Add(selector(t)))
        {
            return true;
        }
    }
    return false;
}
like image 27
Jake Pearson Avatar answered Sep 28 '22 18:09

Jake Pearson