VB.NET Remove Duplicates From ListRemove duplicate elements from a List with the Distinct extension method.
dot net perls
Remove duplicates, List.
A List contains duplicate elements, but these are not needed. We remove duplicates in many ways, with loops, with algorithms of varying speed.
But with the Distinct extension method, we remove these duplicates with a single function call. Collections like the SortedSet can be used to dedupe as we go along.
The Distinct method is part of System.Linq. We need a newer version of VB.NET to use it. Distinct internally loops over all elements in the collection and eliminates duplicates.
ToList We need to invoke ToList, another extension, after calling Distinct to convert back into a list.
Note Distinct returns an IEnumerable collection, not a List. But with ToList we convert it easily back into a List.
VB.NET program that filters duplicates
' Create list and add values.
Dim values As List(Of Integer) = New List(Of Integer)
' Filter distinct elements, and convert back into list.
Dim result As List(Of Integer) = values.Distinct
' Display result.
element As Integer In result
Notes, above example.
We create a list with the elements 1, 2, 2, 3, 3 and 3. After we call Distinct and convert it back into a List, we have a list of elements 1, 2 and 3.
Tip Distinct will also work on string values and other value types. For objects, an equality comparer is needed on the type.
Consider adding elements to a Dictionary or a SortedSet to eliminate duplicates as we go along. You can use Keys and ToList to get a List from a Dictionary.
A summary. Often problems can be solved in simple, or complex, ways. For removing duplicates from a list, loops may be used. But this may lead to greater total program complexity.
© 2007-2021 sam allen. send bug reports to firstname.lastname@example.org.