Click here to Skip to main content
15,914,160 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Remove duplicate entries from string array

Rate me:
Please Sign up or sign in to vote.
3.00/5 (5 votes)
4 Mar 2010CPOL 37.1K   5   2
This VS2008 or higher extension uses a LINQ statement to remove duplicate items from a string array but is not case sensitive, also you might like to leave the sort/order-by in the extension or remove it.ExampleDim Names() As String = {"Bob", "Mary", "bob", "Bob", "Jane", "Kevin",...
This VS2008 or higher extension uses a LINQ statement to remove duplicate items from a string array but is not case sensitive, also you might like to leave the sort/order-by in the extension or remove it.

Example
VB
Dim Names() As String = {"Bob", "Mary", "bob", "Bob", "Jane", "Kevin", "Jane"}
Names = Names.RemoveDuplicates
For Each Name As String In Names
    Console.WriteLine(Name)
Next


Returns
VB
bob
Bob
Jane
Kevin
Mary


Extension (place in code module)
XML
<System.Diagnostics.DebuggerStepThrough()> _
<System.Runtime.CompilerServices.Extension()> _
Public Function RemoveDuplicates(ByVal sender As String()) As String()
    Return (From value In sender Select value Distinct Order By value).ToArray
End Function

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer
United States United States
Microsoft MVP, Uses Microsoft Visual Studio ecosystem building web and desktop solutions

Comments and Discussions

 
Generalmy vote of 1 Pin
MyBlindy4-Mar-10 7:51
MyBlindy4-Mar-10 7:51 
GeneralRe: my vote of 1 Pin
karenpayne4-Mar-10 9:12
karenpayne4-Mar-10 9:12 
The function is called RemoveDuplicates because it returns an array with distinct items as shown between the original string array and the returned string array. The original intent was dealing with values sent to me where I didn't have control over them and figured others might like this too as it is or modifiy it to their task at hand.

Example of what I was dealing with
Private Sub CodeIHaveNoControlOver()
    Dim Values As String() = {"Bob", "Mary", "bob", "Bob", "Jane", "Kevin", "Jane"}
    Demo(Values)
End Sub
Private Sub Demo(ByVal Values() As String)
    Dim query = (From value In Values Select value Distinct Order By value).ToArray
    ComboBox1.Items.AddRange(query)
End Sub
Kevin S. Gallagher
Programming is an art form that fights back

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.