phillip Posted April 3, 2006 Posted April 3, 2006 (edited) I have an array containing letters and numbers that im trying to sort. using the array sort method i'm not geting the results im after Example A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A20 Is being sorted. A1 A10 A11 A2 A20 A3 A4 A5 A6 A7 A8 A9 Edited April 3, 2006 by phillip Quote phillip Restall
mskeel Posted April 3, 2006 Posted April 3, 2006 It looks like the sort method is sorting the entries as strings (alphabetical order where 10 comes before 9). There is a sort method for the Array Class that takes an IComparer as an argument. It looks like you'll have to write a class that impliments the IComparer interface to get the desired sort that you want. There is tons of good info on the internet to help you out. Here's some MSDN info on the method you want with a mediocre example. That should be enough to get you started. Quote
Administrators PlausiblyDamp Posted April 3, 2006 Administrators Posted April 3, 2006 The sort function is sorting them correctly based on the elements being strings. If you desire a different sort order then you might want to look at creating a customised implementation of IComparer. The following snippet should give you a basic idea. Class Testing Implements IComparer Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare Dim x1 As String, y1 As String x1 = DirectCast(x, String) y1 = DirectCast(y, String) Dim i1, i2 As Integer i1 = Integer.Parse(x1.Substring(1)) i2 = Integer.Parse(y1.Substring(1)) If i1 > i2 Then Return 1 If i1 < i2 Then Return -1 Return 0 End Function End Class This can then be called from a method like Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim a() As String = {"a1", "a10", "a3"} Dim x As IComparer Array.Sort(a, New Testing) End Sub Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
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.