LINQ Distinct Method Example

Linq distinct method is used when we want to remove duplicate element from any collection object, here we learn how to use linq distinct operator.

Here are the Distinct operator syntax, we also can create our extension methods.

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);

LINQ Distinct operator c# example

Let’s learn distinct with example, we will try to remove all duplicate names in string list using distinct operator.

using System.Collections.Generic;
using System.Linq;

string[] colors = { "red", "blue", "red", "blue", "white", "green", "yellow", "green" };

var filteredColors = colors.Distinct();

foreach (var name in filteredColors)
{
    Console.WriteLine(name);
}

If you run the above code, you will see all repetitive color names has been removed, in result there is no duplicate value.

You can write similar code to remove duplicate number from any integer array.

Use Distinct for custom object property

So far we have seen how to use linq distinct to remove duplicate number or string from an array, which is very simple!

Now we see how to distinct based on some property values of any custom object, for example we have student list with duplicate email ids, now we want to remove all duplicate emails.

Here is an example, i have done based on Firstname property, you can use any property you want.

var stuList = new List<Student>();
stuList.Add(new Student() { Firstname = "John", Score = 70 });
stuList.Add(new Student() { Firstname = "Ajay", Score = 82 });
stuList.Add(new Student() { Firstname = "Ajay", Score = 82 });
stuList.Add(new Student() { Firstname = "Ruby", Score = 60 });
stuList.Add(new Student() { Firstname = "Archana", Score = 65 });
stuList.Add(new Student() { Firstname = "Archana", Score = 65 });
stuList.Add(new Student() { Firstname = "John", Score = 70 });


var filterStuList =stuList.Select(s => s.Firstname).Distinct();
foreach (var item in filterStuList)
{
	Console.WriteLine(item);
}

In above code, when we print the result on console, we get all unique name, duplicate names are removed successfully.

However, the problem with above solution is, it returns only the property we select, not the whole object.

Distinct object based on property value

Here we see how to distinct object based on any properly value, and this time we want to get the custom object list, not the property list.

In .net linq there is no built-in method which can get the distinct object list directly, so we have to write some additional code.

We create an extension class and create extension method with following code.

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }

Now call the above DistinctBy method on any custom object collection and the select the property name you want to distinct with, this method will return distinct object list.

var stuList = new List<Student>();
stuList.Add(new Student() { Firstname = "John", Score = 70 });
stuList.Add(new Student() { Firstname = "Ajay", Score = 82 });
stuList.Add(new Student() { Firstname = "Ajay", Score = 82 });
stuList.Add(new Student() { Firstname = "Ruby", Score = 60 });
stuList.Add(new Student() { Firstname = "Archana", Score = 65 });
stuList.Add(new Student() { Firstname = "Archana", Score = 65 });
stuList.Add(new Student() { Firstname = "John", Score = 70 });

var filterStuList = stuList.DistinctBy(s=>s.Firstname);

foreach (var item in filterStuList)
{
	Console.WriteLine(item.Firstname);
}

See in result, the method stuList.DistinctBy(s=>s.Firstname); has returned the student list with unique student name.

You may be interested in following tutorial

 
LINQ Distinct Method Example
LINQ (language integrated query) allow you to write query on database objects like ado.net, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join Asp.net MVC Course