Hello devz,

The Distinct extension from System.Linq is really useful but the DistinctBy a property is missing. So we will create our own DistinctBy extension. No worries, it’s really easy.

What is DistinctBy?

DistinctBy is a very simple extension snippet for C# which allows the developer to remove duplicated objects in a collection based on one of its properties (with a lambda expression as a parameter).

For example: myCollection.DistinctBy(x => x.Color);

Here is the snippet for the DistinctBy extension:

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) { return items.GroupBy(property).Select(x => x.First()); }
Code language: C# (cs)

Pretty straightforward, we regroup all the objects in a collection based on the targeted property, then we only keep the first one for each group.

So now you can just call the DistinctBy extension on a collection to get a collection of unique items:

var uniqueCollection = collectionWithDuplicates.DistinctBy(x => x.MyProperty).ToList();
Code language: C# (cs)

Why is DistinctBy useful?

Let’s use a simple example:

We have a collection of 6 hats with different colors, where 2 of them are blue, 2 greens and 2 reds. We just want a collection of hats with the different possibilities of colors. With the DistinctBy the result will be a collection of 3 items: 1 blue, 1 green and 1 red hat.

Happy coding!  🙂