List Remove Duplicates Example
This page was last reviewed on Mar 21, 2023.
Dot Net Perls
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.
An example. 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.
Start We create a list with some duplicate numbers. After we call Distinct and convert it back into a List, we have a list of 1, 2 and 3.
Then 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.
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 Module
1 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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 21, 2023 (edit).
© 2007-2024 Sam Allen.