Several methods of repeated items
One of the simplest and easy -to -read solutions is to use Linq (Language Integration). This feature is introduced in .NET 3, providing a statement method to query and convey data. The following is an example of linq:
Filter the repetitive elements in the
list, and return a new listList<T> withDupes = LoadSomeData(); List<T> noDupes = withDupes.Distinct().ToList();
Methods transform the generated Distinct()
to withDupes
. noDupes
ToList()
If you are already using Linq expressions, this method is very convenient. IEnumerable
List
Another choice is to use HashSet, which is a collection type designed for fast search and efficient repeated detection. The following is the method you can perform this operation:
<初> Initially empty. We traversed each project in <的> and tried to add it to the collection. Since HashSet is not allowed to repeat, only the only project can be successfully added. Finally, the generated collection uses <的> to return back to List.
This method provides O (N) performance for insertion and search operations.
HashSet<T> hashSet = new HashSet<T>(); foreach (var item in withDupes) { hashSet.Add(item); } List<T> noDupes = new List<T>(hashSet);
HashSet hashSet
withDupes
The third method involves the use of Dictionary to track the unique element: noDupes
<作> Temporary storage for the unique element. We traversed the <列> list to check whether each item exists in the dictionary. If not, we add it to the dictionary and
list.This method also provides O (N) complexity, but it needs to create additional data structures for tracking uniquely.
<合> Select the right method
Dictionary<T, bool> dict = new Dictionary<T, bool>(); List<T> noDupes = new List<T>(); foreach (var item in withDupes) { if (!dict.ContainsKey(item)) { dict.Add(item, true); noDupes.Add(item); } }
The above is the detailed content of How Can I Efficiently Remove Duplicates from a C# List?. For more information, please follow other related articles on the PHP Chinese website!