Menu

Various Ways to Get Distinct Values from a List<T> using LINQ

This article talks about the various scenarios regarding filtering distinct values from the List. One practical example is if you have a list of products and wanted to get the distinct values from the list. To make it more clear let’s take an example. Consider that we have this model below that houses the following properties:

The method above returns a list of Products by adding a dummy data to the List just for the simplicity of this demo. In a real scenario you may want to query your database and load the result to your model. Now let’s bind the Products data in GridView.

If you noticed there are few items above that contain the same values or commonly called "duplicate" values. Now let’s try to get the distinct row values from the list using the LINQ Distinct function. The code now would look like this:

Unfortunately, running the code will still give you the same output. This means that the Distinct LINQ function doesn’t work at all. I was surprised and my first reaction was like…

What??? Really???

Yes, it doesn’t work as expected! This is because the Distinct method uses the Default equality comparer to compare values under the hood. And since we are dealing with reference type object then the Distinct will threat the values as unique even if the property values are the same.

The Distinct operator has an overload method that lets you pass an instance of IEqualityComparer. So for this approach we created a class “ProductComparer” that implements the IEqualityCompaper. Here’s the code to use it:

The approach above is my preferred option because it allows me to implement my own GetHashCode and Equals methods for comparing custom types. Also getting into a habit of making interfaces makes your code more reusable and readable.

Output

As you observed the duplicate values are now gone. Now here’s another scenario. What if we want to get the distinct values for a certain field in the list? For example get the distinct “Make” values such as Samsung, Apple, HTC, Nokia and Sony and then populate the result to a DropDownList control for filtering purposes. I was hoping that the Distinct function has an overload that can compare values based on a property or field like GetProducts().Distinct(o => o.PropertyToCompare) but then again it doesn’t seem to have that overload. So I came up with the following workarounds: