Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

Posted
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.

  • *Experts*
Posted (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 by mutant

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...