-
Jul 8th, 2018, 08:32 PM
#1
Thread Starter
New Member
sorting problem
Hi there,
i have got the following list:
1
1-1
1-2
2
2-1
2-2
2-3-1
2-3-2
3
4
How can i sort this list , that i get the following:
1
2
3
4
1-1
1-2
2-1
2-2
2-3-1
2-3-2
Thnx in advance!
Greetz chris
-
Jul 8th, 2018, 08:58 PM
#2
Re: sorting problem
Well, it looks like a two pass to me, sorting by length first, and then sorting each of those groups. The second sort looks like it would work alphabetically.
But if you have two digit numbers between the dashes, i.e. 2-10-4, would that be sorted alphabetically (coming before 2-3-1), or numerically (coming after 2-3-2), or would that be sorted first by length (6 characters, so would be in a group after the 5 character strings).
Or should the "-", be treated as a column separator, so 2-3-1 is three columns, and 2-10-4 is also three columns, so are part of the same group that are to be sorted together.
-
Jul 8th, 2018, 09:02 PM
#3
Re: sorting problem
Assuming a List(Of String) and a desire to sort numerically:
vb.net Code:
Module Module1 Sub Main() Dim items As New List(Of String) From {"1", "1-1", "1-2", "2", "2-1", "2-2", "2-3-1", "2-3-2", "3", "4"} items.Sort(Function(item1, item2) Dim arr1 = item1.Split("-"c) Dim arr2 = item2.Split("-"c) 'Compare by length first. Dim result = arr1.Length.CompareTo(arr2.Length) If result = 0 Then 'Lengths are equal so compare parts. For i = 0 To arr1.GetUpperBound(0) result = CInt(arr1(i)).CompareTo(CInt(arr2(i))) If result <> 0 Then Exit For End If Next End If Return result End Function) For Each item As String In items Console.WriteLine(item) Next Console.ReadLine() End Sub End Module
That's using a lambda expression, which is functionally equivalent to using a named method like this:
vb.net Code:
Module Module1 Sub Main() Dim items As New List(Of String) From {"1", "1-1", "1-2", "2", "2-1", "2-2", "2-3-1", "2-3-2", "3", "4"} items.Sort(AddressOf Compare) For Each item As String In items Console.WriteLine(item) Next Console.ReadLine() End Sub Function Compare(item1 As String, item2 As String) As Integer Dim arr1 = item1.Split("-"c) Dim arr2 = item2.Split("-"c) 'Compare by length first. Dim result = arr1.Length.CompareTo(arr2.Length) If result = 0 Then 'Lengths are equal so compare parts. For i = 0 To arr1.GetUpperBound(0) result = CInt(arr1(i)).CompareTo(CInt(arr2(i))) If result <> 0 Then Exit For End If Next End If Return result End Function End Module
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|