Efficient Duplicate Removal from C# Generic Lists
This guide demonstrates effective techniques for removing duplicate entries from generic lists in C#. We'll explore two primary methods:
Method 1: LINQ's Distinct()
Method
For .NET Framework 3.0 and later, the LINQ Distinct()
method offers a concise solution:
<code class="language-csharp">List<T> listWithDuplicates = LoadSomeData(); List<T> listWithoutDuplicates = listWithDuplicates.Distinct().ToList();</code>
Distinct()
generates a new list containing only unique elements.
Method 2: Utilizing a HashSet
HashSet<T>
provides a more efficient approach for larger datasets:
<code class="language-csharp">List<T> listWithDuplicates = LoadSomeData(); HashSet<T> listWithoutDuplicates = new HashSet<T>(listWithDuplicates);</code>
HashSet<T>
inherently stores unique items, eliminating duplicates during the creation process. This method is generally faster than Distinct()
for large lists.
The above is the detailed content of How Can I Efficiently Remove Duplicates from a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!