C# - Example of LINQ Distinct() Method

Learn about the Linq Distinct() method and its C# implementation with an example. By Nidhi Last updated : April 01, 2023

Here we will find all unique integer numbers using Linq Distinct() method. Then we will print all the distinct values on the console screen.

C# program to demonstrate the example of LINQ Distinct() method

The source code to demonstrate Linq Distinct() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate Linq Distinct() method.

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

class Demo {
  static void Main(string[] args) {
    List < int > Numbers = new List < int > () {
      10,
      20,
      20,
      30,
      40,
      40,
      10,
      50,
      60
    };

    var result = Numbers.Distinct();

    foreach(var distinct in result) {
      Console.WriteLine(distinct + " ");
    }
  }
}

Output

10
20
30
40
50
60
Press any key to continue . . .

Explanation

In the above program, we created the list of integer numbers.

List<int> Numbers = new List<int>() { 10, 20, 20, 30, 40, 40, 10, 50, 60 };

In the above list, some values are duplicates. Then we find all unique values using the below code.

var result = Numbers.Distinct();

Then we print all distinct values on the console screen using the below code.

foreach (var distinct in result)
{
    Console.WriteLine(distinct + " ");
} 

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.