user137348 user137348 - 3 months ago 14
C# Question

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.

Answer

I think this method will work.

public static bool ContainsDuplicates<T>(this IEnumerable<T> source, Func<T, T1> selector)
{
    var d = new HashSet<T1>();
    foreach(var t in source)
    {
        if(!d.Add(selector(t)))
        {
            return true;
        }
    }
    return false;
}