
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
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
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
Advertisements