Home > Backend Development > C++ > How Can I Efficiently Remove Duplicates from a Generic List in C#?

How Can I Efficiently Remove Duplicates from a Generic List in C#?

DDD
Release: 2025-01-29 02:21:08
Original
287 people have browsed it

How Can I Efficiently Remove Duplicates from a Generic List in C#?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template