Help with removing duplicates  and sorting data  from string variable using vb.net

vcharles
vcharles used Ask the Experts™
on
Hi,

How do I remove  duplicates from a string variable and sort the values? for example is S = '55','44','11','2','1" how do i obtain S = '1','2','11','44','55'?

Thanks,

Victor
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
sorting is easy use 'Array.Sort(s)' but this does an alphabetic sort

Another way is to use lists
  Sub Main()
        Dim s As List(Of Integer) = New List(Of Integer)
        s.Add(55)
        s.Add(55)
        s.Add(44)
        s.Add(11)
        s.Add(2)
        s.Add(1)
        s.Add(1)
        s.Sort()
        For Each item As String In s
            Console.Write(item & " ")
        Next
        Console.WriteLine()
        Dim result As List(Of Integer) = s.Distinct().ToList
        For Each element As Integer In result
            Console.WriteLine(element)
        Next
        Console.ReadLine()

    End Sub

Open in new window

Top Expert 2015

Commented:
If this is a follow up on your previous question, then I would simply suggest that you do the job in the query that you use to retrieve the data from the database. Simply add a DISTINCT and an ORDER BY clause to your SQL command, and your DataTable will come out without the duplicates and already ordered, so the code you have to build your string will automatically present it  correctly.

You probably know the ORDER BY. If DISTINCT is new for you, you will find a good discussion with examples of its use at http://www.techonthenet.com/sql_server/distinct.php

Author

Commented:
Thank you for both solutions.
Victor
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

        Dim s = "'55','44','11','2','1','44','55'"
        Dim trimmed = s.TrimStart("'").TrimEnd("'")
        Dim arr = trimmed.Split(New String() {"','"},
                            StringSplitOptions.RemoveEmptyEntries).
                            Select(Function(x) CInt(x))
        Dim result = "'" & String.Join("','", arr.Distinct.OrderBy(Function(x) x).ToArray) & "'"
        MsgBox(result)

Open in new window

Oops, just read your previous question. You can use:
Dim S As String = "'" & String.Join ("','", _
(From id In dt.AsEnumerable() _
Select CInt(id.Field(Of String)("ID"))). _
Distinct().OrderBy(Function(x) x).ToArray) & "'"

Open in new window


PS. If your ID field is already integer type (not string) you can ommit CInt()

Author

Commented:
Thank You.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial