C# program to print unique values from a list

CsharpProgrammingServer Side Programming

Set the list.

List < int > list = new List < int > ();
list.Add(99);
list.Add(49);
list.Add(32);

To get unique elements.

List<int> myList = list.Distinct().ToList();

Here is the complete example to display unique values from a list.

Example

 Live Demo

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

public class Demo {
   public static void Main() {
      List < int > list = new List < int > ();
      list.Add(55);
      list.Add(45);
      list.Add(55);
      list.Add(65);
      list.Add(73);
      list.Add(24);
      list.Add(65);

      Console.WriteLine("Initial List...");
      foreach(int a in list) {
         Console.WriteLine("{0}", a);
      }

      List < int > myList = list.Distinct().ToList();
      Console.WriteLine("Unique elements...");
      foreach(int a in myList) {
         Console.WriteLine("{0}", a);
      }
   }
}

Output

Initial List...
55
45
55
65
73
24
65
Unique elements...
55
45
65
73
24
raja
Published on 21-Aug-2018 08:38:57
Advertisements