How to remove duplicates from Generic List (Of String)
I will show you a two ways how to clean up generic list of dupes.
Say that you have a list of Baby names like following:
Dim MyList As New List(Of String)
MyList.Add("Simon")
MyList.Add("Denholm")
MyList.Add("Denis")
MyList.Add("Deniz")
MyList.Add("Denley")
MyList.Add("Dennis")
MyList.Add("Dennison")
MyList.Add("Denton")
MyList.Add("Denver")
MyList.Add("Denzel")
MyList.Add("Denzil")
MyList.Add("Deo")
MyList.Add("Derain")
MyList.Add("Derby")
MyList.Add("Derek")
MyList.Add("Derex")
MyList.Add("Dermot")
MyList.Add("Derrell")
MyList.Add("Derren")
MyList.Add("Derrick")
MyList.Add("Derron")
MyList.Add("Derry")
MyList.Add("Derward")
MyList.Add("Derwent")
MyList.Add("Derwin")
MyList.Add("Derwood")
MyList.Add("Derwyn")
MyList.Add("Denholm")
MyList.Add("Denley")
MyList.Add("Derrell")
' the latest 3 are dupes
The simplest way to remove the dupes from your list is to use the Distinct function.
' very simple
Dim UniqueValuesOne As List(Of String) = MyList.Distinct().ToList()
' Check the results
For Each Str As String In UniqueValuesOne
Console.WriteLine(Str)
Next
the another way is to not remove duplicates, but rather create a new List only containing unique elements from the original list.
Dim UniqueValuesTwo As New List(Of String)
For Each str As String In MyList
If Not UniqueValuesTwo.Contains(str) Then
' add unique value
UniqueValuesTwo.Add(str)
End If
Next
' Check the results
For Each Str As String In UniqueValuesTwo
Console.WriteLine(Str)
Next
RSS 2.0 Comments Feed | Leave a Response | Trackback
Leave a Reply