Remove duplicates from a List in C#


Use the Distinct() method to remove duplicates from a list in C#.

Firstly, add a new list −

List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);

To remove duplicate elements, use the Distinct() method as shown below −

List<int> distinct = arr1.Distinct().ToList();

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      // Removing duplicate elements
      List<int> distinct = arr1.Distinct().ToList();
      Console.WriteLine("List after removing duplicate elements ...");
      foreach (int res in distinct) {
         Console.WriteLine("{0}", res);
      }
   }
}

Output

Initial List ...
10
20
30
40
50
30
40
50
List after removing duplicate elements ...
10
20
30
40
50

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements