LINQ Distinct Method

In LINQ, the Distinct method or operator is useful to get only distinct elements from the collection.

 

Following is the pictorial representation of the LINQ distinct method. 

 

LINQ Distinct Method with Example

 

The LINQ distinct method will remove duplicate elements from the collection and return distinct or unique elements.

Syntax of LINQ Distinct Method

Following is the syntax of the distinct method to get unique elements from the collection.

 

C# Code

 

IEnumerable<int> result = numbers.Distinct();

VB.NET Code

 

Dim result As IEnumerable(Of Integer) = numbers.Distinct()

If you observe the above syntax, we applied the Distinct method on the “numbers” collection to get only distinct elements from the collection.

Example of LINQ Distinct Method

Following is the example of using the LINQ Distinct method.

 

C# Code

 

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

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] countries = { "UK", "uk", "Australia", "INDIA", "india", "USA" };
      IEnumerable<string> result = countries.Distinct(StringComparer.OrdinalIgnoreCase);
      foreach (var item in result)
      {
        Console.WriteLine(item);
      }
      Console.ReadLine();
    }
  }
}

VB.NET

 

Module Module1

Sub Main()
Dim countries As String() = {"UK", "uk", "Australia", "INDIA", "india", "USA"}
Dim result As IEnumerable(Of String) = countries.Distinct(StringComparer.OrdinalIgnoreCase)
For Each item In result
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above example, we applied the Distinct method with StringComparer.OrdinalIgnoreCase case property; otherwise, it will perform the operation with case sensitivity on “countries” collection, and it will treat “INDIA” and “india” as different.

Result of LINQ Distinct Method Example

Following is the result of the LINQ distinct method example.

 

UK
Australia
India
USA

This is how we can use LINQ distinct method in c#, vb.net to get unique elements from the collection.