Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

LINQ / C#

LINQ Distinct Operator

LINQ Distinct operator is used for removing duplicates elements from the sequence (list). Distinct operator comes under Set operators category in LINQ query operators.

For example, we have one collection A = { 1, 2, 3, 3, 4, 4, 5}. In this collection 3 and 4 elements are repeated two times and we have to create a new sequence which takes these duplicates only one time. So we use distinct operator over A collection. C = A.distinct(); C = { 1, 2, 3, 4, 5}.

Distinct operator is only available in Method Syntax and not available in Query Syntax.

Below is the syntax of Distinct operator.

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

There are two overload methods. First one takes no parameter and second one takes IEqualityComparer parameter to compare complex types.

C# LINQ Distinct Example

string[] employeesNames = { "Asutosh", "Kapil", "Sumit", "Rajat", "Preeti", "Sumit", "Kanupriya", "Kapil" };

var distinctEmployees = employeesNames.Distinct();

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

Result
------
Asutosh
Kapil
Sumit
Rajat
Preeti
Kanupriya

In the above example, “Kapil” and “Sumit” names are repeated in employeeNames collection. By using Distinct operator we get a new collection which remove duplicate name.

Distinct with IEqualityComparer

By default Distinct operator can not compare complex types. For this, we need to use second overload which takes an instance of IEqualityComparer. IEqualityComparer is used for comparing complex types. IEqualityCompare has two methods Equals and GetHashCode. Both methods are compulsory to implement.

internal class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
}

internal class StudentNameComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        if (string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
        return false;
    }

    public int GetHashCode(Student obj)
    {
        return obj.Name.GetHashCode();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        List<Student> students = new List<Student>();

        students.Add(new Student { ID = 1, Name = "Asutosh" });
        students.Add(new Student { ID = 1, Name = "Kapil" });
        students.Add(new Student { ID = 1, Name = "Sumit" });
        students.Add(new Student { ID = 1, Name = "Rajat" });
        students.Add(new Student { ID = 1, Name = "Preeti" });
        students.Add(new Student { ID = 1, Name = "Sumit" });
        students.Add(new Student { ID = 1, Name = "Kanupriya" });
        students.Add(new Student { ID = 1, Name = "Kapil" });

        var distinctStudents = students.Distinct(new StudentNameComparer());

        foreach (var student in distinctStudents)
        {
            Console.WriteLine(student.Name);
        }
    }
}

Result
------
Asutosh
Kapil
Sumit
Rajat
Preeti
Kanupriya