Welcome to Dream.In.Code
Getting Help is Easy!

Join 132,118 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,983 people online right now. Registration is fast and FREE... Join Now!




Custom Sorting

 
Reply to this topicStart new topic

> Custom Sorting, Implement an IComparer.Compare

AdamSpeight2008
Group Icon



post 14 Jul, 2008 - 12:33 PM
Post #1


Start a new windows project
Add a button and listbox
Insert the following code into form1
vb

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a() As String = {"4", "5", "10", "12", "14", "15", "7", "8", "9", "3", "18", "16", "15", "100", "13", "55"}
Dim sc As New NumericComparer(True)
Array.Sort(a, sc)
ListView1.Items.Clear()
For i As Integer = 0 To a.Length - 1
ListBox1.Items.Add(a(i))
Next
End Sub
End Class


Implementing the IComparer.Compare
Add a new class insert following code.

vb

Public Class NumericComparer
Implements IComparer
Dim mText As Boolean = False
Public Sub New(ByRef sorttype As NumericSort)
mText = sorttype
End Sub

Public Enum NumericSort
Textual = True
Numerical = False
End Enum

' Compare the two employees.
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
If mText = False Then
Dim txtx As Double = CDbl(x)
Dim txty As Double = CDbl(y)
Select Case True
Case txtx < txty : Return -1
Case txtx = txty : Return 0
Case txtx > txty : Return 1
End Select
Else
Dim txtx As String = CStr(x)
Dim txty As String = CStr(y)
Return String.Compare(txtx, txty)
End If

End Function
End Class





Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/21/08 10:33AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month