HOW to fetch Unique data from LINQ using the Distinct Method?

HOW to fetch Unique data from LINQ using the Distinct Method?

Last updated:9/24/2021 3:11:38 AM

1 Answers

Ravi Vishwakarma
Ravi Vishwakarma

In LINQ, the Distinct method or operator is used to get only distinct elements from the collection or list. In another word these distinct method doesn’t accept the duplicate elements, means remove the duplicate value make its single value.

Syntax

collection1.Distinct ( collection2)

Example

using System;

using System.Collections.Generic;
using System.Linq;
public class Program
{
 public static void Main()
 {
  List<string> count1= new List<string>() { 'UK', 'Australia', 'India', 'USA', 'India', 'UAE', 'Canada', 'Uk', 'China', 'Pok' };
  // ignore the case
  //List<string> list = count1.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  List<string> list = count1.Distinct().OrderBy( str => str).ToList();
  list.ForEach( country => Console.WriteLine(country) );
  Console.ReadLine();
 }
}

Output

after using orderby() method result in ascending order

Australia

Canada
China
India
Pok
UAE
Uk
UK
USA

Answer