How to Remove Duplicates from List in C# Easily
To remove duplicates from a list in C#, use
list.Distinct() from LINQ which returns unique elements. Alternatively, convert the list to a HashSet which automatically removes duplicates.Syntax
Use Distinct() method from LINQ to get unique elements from a list. It returns an IEnumerable of distinct items.
Alternatively, create a HashSet<T> from the list which stores only unique values.
csharp
var uniqueList = list.Distinct().ToList(); var uniqueSet = new HashSet<T>(list);
Example
This example shows how to remove duplicates from a list of integers using Distinct() and HashSet. Both methods produce a list with unique values.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 }; // Using Distinct() List<int> distinctList = numbers.Distinct().ToList(); Console.WriteLine("Using Distinct(): " + string.Join(", ", distinctList)); // Using HashSet HashSet<int> uniqueSet = new HashSet<int>(numbers); Console.WriteLine("Using HashSet: " + string.Join(", ", uniqueSet)); } }
Output
Using Distinct(): 1, 2, 3, 4, 5
Using HashSet: 1, 2, 3, 4, 5
Common Pitfalls
- Forgetting to call
ToList()afterDistinct()if you need a list instead ofIEnumerable. - Using
HashSetchanges the order of elements because it does not preserve insertion order. - Modifying the original list while iterating can cause errors.
csharp
/* Wrong: Using Distinct() but not converting to list when list needed */ var distinctEnumerable = numbers.Distinct(); // distinctEnumerable is IEnumerable<int>, not List<int> /* Right: Convert to list */ var distinctList = numbers.Distinct().ToList();
Quick Reference
Use Distinct() for simple unique filtering with order preserved. Use HashSet for fast uniqueness but unordered results.
| Method | Description | Order Preserved | Return Type |
|---|---|---|---|
| Distinct() | Returns unique elements preserving order | Yes | IEnumerable |
| HashSet | Stores unique elements, fast lookup, unordered | No | HashSet |
Key Takeaways
Use list.Distinct().ToList() to get a list without duplicates while keeping order.
HashSet removes duplicates but does not keep the original order.
Always convert Distinct() result to a list if you need list methods.
Avoid modifying a list while iterating to prevent errors.
Choose the method based on whether order matters and performance needs.