Remove
duplicates, List
A VB.NET List
may contain unneeded duplicate elements. 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.
List
, we have a list of 1, 2 and 3.ToList
, another extension, after calling Distinct to convert back into a list.IEnumerable
collection, not a List
. But with ToList
we convert it easily back into a List
.Module Module1 Sub Main() ' Create list and add values. Dim values As List(Of Integer) = New List(Of Integer) values.Add(1) values.Add(2) values.Add(2) values.Add(3) values.Add(3) values.Add(3) ' Filter distinct elements, and convert back into list. Dim result As List(Of Integer) = values.Distinct().ToList ' Display result. For Each element As Integer In result Console.WriteLine(element) Next End Sub End Module1 2 3
Dictionary
, SortedSet
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
.
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.