lilgirl Posted March 20, 2004 Posted March 20, 2004 Hi, I have an array that contains strings like this: "Connection_1.xml" "Connection_10.xml" "Connection_2.xml" "Connection_3.xml" I would like to sort the array so that "Connection_10.xml" is last rather than 2nd in the list. Can anyone suggest a way to do this? Thanks. Quote
georgepatotk Posted March 20, 2004 Posted March 20, 2004 There are many ways you can do it. Sequential sort, bubble sort, and so others. hava a look on this http://www-ee.eng.hawaii.edu/Courses/EE150/Book/chap10/subsection2.1.2.2.html Quote George C.K. Low
*Experts* mutant Posted March 20, 2004 *Experts* Posted March 20, 2004 Use the shared method of the Array class to sort your array. Quote
Jaco Posted March 20, 2004 Posted March 20, 2004 Use the shared method of the Array class to sort your array. If you try this, you'll see that you have exactly the original problem. i.e., the result is: "Connection_1.xml" "Connection_10.xml" "Connection_2.xml" "Connection_3.xml" You need to either write your own sort or implement a comparer class and pass this to the System.Array Sort method. Quote
*Experts* mutant Posted March 20, 2004 *Experts* Posted March 20, 2004 (edited) True, I should have looked closely at the data. Here is how you can implement your own IComparer like Jaco mentioned: Imports System.Text.RegularExpressions Public Class StringComparer Implements IComparer 'implement the comparer so the Sort method will take it Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare 'get the first number from the x object that was passed using regular expressions so it very easy 'to find numbers that are more then 1 digit long Dim num1 As Integer = Convert.ToInt32(Regex.Match(x.ToString(), "[0-9]+").Value) 'get the first number for the y object Dim num2 As Integer = Convert.ToInt32(Regex.Match(y.ToString(), "[0-9]+").Value) 'if the number from x is bigger then return 1 (or any positive number) If num1 > num2 Then Return 1 'if they are equal return 0 ElseIf num1 = num2 Then Return 0 'if x is less then y return -1 (or any negative number) Else Return -1 End If End Function End Class Then you can pass in the comparer to the Sort method: Array.Sort(yourarray, new StringComparer) Edited March 20, 2004 by mutant Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.