LINQ Distinct Method

  Total Views : 172
  Comments : 0
 
  Keywords : Linq distinct operator in c# / vb.net with example, How to use linq enumerable.distinct method to get distinct elements from the collection in c# / vb.net with example

Here we will learn LINQ Distinct method in c#, vb.net with example and how to use LINQ Distinct method to get distinct elements from the collection in c#, vb.net with example.

LINQ Distinct Method

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

 

Following is the pictorial representation of 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 using 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 above syntax we applied Distinct method on “numbers” collection to get only distinct elements from the collection.

Example of LINQ Distinct Method

Following is the example of using 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 above example, we applied Distinct method with StringComparer.OrdinalIgnoreCase case property otherwise it will perform operation with case sensitivity on “countries” collection and it will treat “INDIA” and “india” are different.

Output of LINQ Distinct Method Example

Following is the result of 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.

 
 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User