Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# program to remove duplicate elements from a List
Declare a list and add elements.
List<int> list = new List<int>(); list.Add(50); list.Add(90); list.Add(50); list.Add(100);
Now, use Distinct() method to get the unique elements only.
List<int> myList = list.Distinct().ToList();
The following is the complete code to remove duplicate elements from a List −
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < int > list = new List < int > ();
list.Add(50);
list.Add(90);
list.Add(50);
list.Add(100);
Console.WriteLine("Initial List...");
foreach(int a in list) {
Console.WriteLine("{0}", a);
}
List < int > myList = list.Distinct().ToList();
Console.WriteLine("New List after removing duplicate elements...");
foreach(int a in myList) {
Console.WriteLine("{0}", a);
}
}
}
Output
Initial List... 50 90 50 100 New List after removing duplicate elements... 50 90 100
Advertisements