Remove duplicates from a List in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 16:18:01
Advertisements