Remove duplicates from List - Update
Hi just a quick example of removing duplicates from a list object, useful for strings or numbers.
Comments and suggests welcome.
Example
vbnet Code:
Public Class Form1
Private Sub ListRemoveDups(ByVal Source As List(Of String), Optional ByVal MatchCase As Boolean = False)
'Sort the array
Source.Sort()
'Do the duplicates remove.
For x As Integer = Source.Count - 1 To 1 Step -1
'Check if we want
If MatchCase Then
'Do the check
If Source(x).ToLower() = Source(x - 1).ToLower() Then
Source.RemoveAt(x)
End If
Else
'Do the check
If Source(x) = Source(x - 1) Then
Source.RemoveAt(x)
End If
End If
Next x
End Sub
Private Sub cmdDemo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDemo.Click
'Remove duplicates from list
Dim names As New List(Of String)
'Add some names
names.Add("Ben")
names.Add("Ben")
names.Add("David")
names.Add("Chris")
names.Add("David")
names.Add("Ben")
names.Add("Chris")
names.Add("david")
'Match Case
ListRemoveDups(names, True)
'Display names
For x As Integer = 0 To names.Count - 1
MessageBox.Show(names(x), "Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
'Return Ben,Chris,david
Next x
End Sub
End Class
Re: Remove duplicates from List
You could also use LINQ for this. Something like:
Code:
Dim uniqueNames = From u In names Distinct
For Each n In uniqueNames
Console.WriteLine(n)
Next
1 Attachment(s)
Re: Remove duplicates from List
Hello again this is an update of the code I submitted this morning. Anyway I now made it into a small little program.
You can give it a source and remove duplicates that is sorted or unsorted
You can also copy or save your output. Hope you like it.
Comments and suggests welcome.
http://i48.tinypic.com/2645r14.png
Re: Remove duplicates from List - Update
When performing such tedious operations I like to rely on LINQ rather than Loops. You should really look into LINQ, its quite powerful ;)
Code:
'remove duplicates
Dim cleanList As List(Of String) = IO.File.ReadAllLines("[FILENAME]").Distinct.ToList
'remove duplicates + null lines
Dim cleanList As List(Of String) = IO.File.ReadAllLines("[FILENAME]").Where(Function(line) Not line.Equals(String.Empty)).Distinct.ToList