Home

Search

VB.NET Remove Duplicates From List

Remove duplicate elements from a List with the Distinct extension method.

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.List

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.LINQ
ToList: We need to invoke ToList, another extension, after calling Distinct to convert back into a list.
ToList
Note: Distinct returns an IEnumerable collection, not a List. But with ToList we convert it easily back into a List.
IEnumerable
VB.NET program that filters duplicates 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 Output 1 2 3

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.

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.DictionarySortedSet

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.

Home
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.