I have a List<> of objects in C# and I need a way to return those objects that are considered duplicates within the list. I do not need the Distinct resultset, I need a
I inadvertently coded this yesterday, when I was trying to write a "distinct by a projection". I included a ! when I shouldn't have, but this time it's just right:
public static IEnumerable DuplicatesBy
(this IEnumerable source, Func keySelector)
{
HashSet seenKeys = new HashSet();
foreach (TSource element in source)
{
// Yield it if the key hasn't actually been added - i.e. it
// was already in the set
if (!seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
You'd then call it with:
var duplicates = cars.DuplicatesBy(car => car.Color);