Current location: Hot Scripts Forums » Programming Languages » Windows .NET Programming » [SOLVED] Sorting a Collection or an ArrayList in VB.NET


[SOLVED] Sorting a Collection or an ArrayList in VB.NET

Reply
  #1 (permalink)  
Old 10-11-04, 09:59 PM
digioz's Avatar
digioz digioz is offline
Community VIP
 
Join Date: Oct 2003
Location: Chicago, IL
Posts: 2,171
Thanks: 3
Thanked 9 Times in 9 Posts
[SOLVED] Sorting a Collection or an ArrayList in VB.NET

Hi All,

A short while ago I was looking for a simple way to sort a collection in VB.NET. I finally found the subroutine I was looking for today and figured other people can use it as well. The following subroutine will sort objects residing in a collection by a property you specify in either ascending or descending order:

For collections (special thanks to Greg Givler's post on FreeVBCode.com):

Code:
 
Public Sub SortCollection(col As Collection, _
  psSortPropertyName As String, pbAscending As Boolean, _
   Optional psKeyPropertyName As String = "")
	
		Dim obj As Object
		Dim i As Integer
		Dim j As Integer
		Dim iMinMaxIndex As Integer
		Dim vMinMax As Object
		Dim vValue As Object
		Dim bSortCondition As Boolean
		Dim bUseKey As Boolean
		Dim sKey As String
	
			bUseKey = (psKeyPropertyName <> "")
	
			For i = 1 To col.Count - 1
				obj = col(i)
				' the vbGet can be replaced with a 
				 'CallType.Get if you
				' want. See VB Language reference for CallByName
		
			vMinMax = CallByName(obj, psSortPropertyName, VbGet)
				iMinMaxIndex = i
	
				For j = i + 1 To col.Count
					obj = col(j)
					vValue = CallByName(obj, _
						psSortPropertyName, VbGet)
	
					If (pbAscending) Then
						bSortCondition = (vValue < vMinMax)
					Else
						bSortCondition = (vValue > vMinMax)
					End If
	
					If (bSortCondition) Then
						vMinMax = vValue
						iMinMaxIndex = j
					End If
	
					obj = Nothing
				Next j
	
				If (iMinMaxIndex <> i) Then
					obj = col(iMinMaxIndex)
	
					col.Remove(iMinMaxIndex)
					If (bUseKey) Then
						sKey = CStr(CallByName(obj, _
						   psKeyPropertyName, VbGet))
						col.Add(obj, sKey, i)
					Else
						col.Add(obj, , i)
					End If
	
					obj = Nothing
				End If
	
				obj = Nothing
			Next i
	
	End Sub
 
' Sample use: 
SortCollection(collection, "EmployeeName", True)

Here is a similar subroutine for an ArrayList (forgot where I found this one):

Code:
 
Public Sub SortObjectCol(ByVal List As ArrayList, ByVal min As 
Integer, _
		ByVal max As Integer, ByVal propName As String)
		Dim last_swap As Integer
		Dim i As Integer
		Dim j As Integer
		Dim tmp As Object

		' Repeat until we are done.
		Do While min < max
			' Bubble up.
			last_swap = min - 1
			' For i = min + 1 To max
			i = min + 1
			Do While i <= max
				' Find a bubble.
				If CallByName(List(i - 1), propName, CallType.Get) > 
CallByName(List(i), propName, CallType.Get) Then
					' See where to drop the bubble.
					tmp = List(i - 1)
					j = i
					Do
						List(j - 1) = List(j)
						j = j + 1
						If j > max Then Exit Do
					Loop While CallByName(List(j), propName, 
CallType.Get) < CallByName(tmp, propName, CallType.Get)
					List(j - 1) = tmp
					last_swap = j - 1
					i = j + 1
				Else
					i = i + 1
				End If
			Loop
			' Update max.
			max = last_swap - 1

			' Bubble down.
			last_swap = max + 1
			' For i = max - 1 To min Step -1
			i = max - 1
			Do While i >= min
				' Find a bubble.
				If CallByName(List(i + 1), propName, CallType.Get) < 
CallByName(List(i), propName, CallType.Get) Then
					' See where to drop the bubble.
					tmp = List(i + 1)
					j = i
					Do
						List(j + 1) = List(j)
						j = j - 1
						If j < min Then Exit Do
					Loop While CallByName(List(j), propName, 
CallType.Get) > CallByName(tmp, propName, CallType.Get)
					List(j + 1) = tmp
					last_swap = j + 1
					i = j - 1
				Else
					i = i - 1
				End If
			Loop
			' Update min.
			min = last_swap + 1
		Loop
	End Sub


	'sample use syntax
	'SortObjectCol(col, 0, col.Count - 1, "ID")
__________________

Last edited by forgueam; 09-15-09 at 12:32 PM. Reason: Testing highlight tag
Reply With Quote
  #2 (permalink)  
Old 07-30-06, 08:23 AM
koncept
Guest
 
Posts: n/a
i know this an old thread but thanks digi, i just stumbled across it in a search and it was exactly what i needed.
Reply With Quote
  #3 (permalink)  
Old 07-30-06, 08:03 PM
digioz's Avatar
digioz digioz is offline
Community VIP
 
Join Date: Oct 2003
Location: Chicago, IL
Posts: 2,171
Thanks: 3
Thanked 9 Times in 9 Posts
You are very welcome bud.
__________________
Reply With Quote
  #4 (permalink)  
Old 03-21-08, 11:56 AM
levienigma levienigma is offline
New Member
 
Join Date: Mar 2008
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Sorting a Collection or an ArrayList in VB.NET

I came across your thread and it has been what I been trying do, thank you. Im still new to .net, and I have a little problem with how to make it work
I have placed this part of code in my button but I replaced "col" with
SortObjectCol(al3, 0, al3.Count - 1, "tax_id")

al3 is my arraylist and I want to sort on "tax_id" but I keep getting an error
I want to sort off datatype "tax_id" can you please help. Thank you

'sample use syntax
'SortObjectCol(col, 0, col.Count - 1, "ID")
Reply With Quote
  #5 (permalink)  
Old 03-21-08, 02:20 PM
levienigma levienigma is offline
New Member
 
Join Date: Mar 2008
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Also it seem that my application is getting stuck in a continued loop when it hits the sort and i dont understand why
Reply With Quote
  #6 (permalink)  
Old 03-21-08, 02:26 PM
digioz's Avatar
digioz digioz is offline
Community VIP
 
Join Date: Oct 2003
Location: Chicago, IL
Posts: 2,171
Thanks: 3
Thanked 9 Times in 9 Posts
Wow! Its been a while since I posted this code (about 4 years to be exact). But I think this topic is important enough to be worthy of further clarification.

I am attaching a sample VS 2005 VB.NET Project to this post. Here is how the sample form looks:

Sorting_Collection_and_ArrayList_1.jpg

Lets say you have a class called "MyData" which holds your actual Data Object:

vb.net Code:
  1. Public Class MyData
  2.         Private m_Value As String
  3.         Public Property Value() As String
  4.             Get
  5.                 Return m_Value
  6.             End Get
  7.             Set(ByVal value As String)
  8.                 m_Value = value
  9.             End Set
  10.         End Property
  11.     End Class

Here are the two functions I wrote to create an arraylist and a collection respectively from the data in the textbox on the form (one item per line):

vb.net Code:
  1. Public Function ToArrayList(ByVal lsString As String) As ArrayList
  2.         Dim laListItems As Array = Split(lsString, vbNewLine)
  3.         Dim laListItems2 As New ArrayList
  4.         Dim loMyData As MyData
  5.         Dim i As Integer
  6.         For i = 0 To laListItems.Length - 1
  7.             loMyData = New MyData
  8.             loMyData.Value = (laListItems(i))
  9.             laListItems2.Add(loMyData)
  10.         Next
  11.         Return laListItems2
  12. End Function
  13.  
  14. Public Function ToCollection(ByVal lsString As String) As Collection
  15.         Dim laListItems As Array = Split(lsString, vbNewLine)
  16.         Dim laCollection As New Collection
  17.         Dim loMyData As MyData
  18.         Dim i As Integer
  19.         For i = 0 To laListItems.Length - 1
  20.             loMyData = New MyData
  21.             loMyData.Value = (laListItems(i))
  22.             laCollection.Add(loMyData)
  23.         Next
  24.         Return laCollection
  25. End Function

All you have to do then is to call the routines above and pass it to the sort subroutines (I turned the subroutines into functions for the purpose of this demo:

vb.net Code:
  1. Private Sub btnSortArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSortArray.Click
  2.         Dim laArrayList As New ArrayList
  3.         Dim laArrayListSorted As New ArrayList
  4.         laArrayList = ToArrayList(txtItemList.Text)
  5.         laArrayListSorted = SortObjectCol(laArrayList, 0, laArrayList.Count - 1, "Value")
  6.     End Sub
  7.     Private Sub btnSortCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSortCollection.Click
  8.         Dim laCollection As New Collection
  9.         Dim laCollectionSorted As New Collection
  10.         laCollection = ToCollection(txtItemList.Text)
  11.         laCollectionSorted = SortCollection(laCollection, "Value", True)
  12.     End Sub

Here is how the sorted objects will then look like:

ArrayList Sorted:
Sorting_Collection_and_ArrayList_2.jpg

Collection Sorted:
Sorting_Collection_and_ArrayList_3.jpg

Try out the project attached bellow and let me know if you got it. remember to put breakpoints at the end of the button click subs to see what's in the sorted objects.

Pete
Attached Files
File Type: zip CollectionsAndArraySort.zip (59.8 KB, 470 views)
__________________
Reply With Quote
  #7 (permalink)  
Old 09-02-09, 04:48 PM
gusadolfo gusadolfo is offline
New Member
 
Join Date: Sep 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Hi digioz i found this code and it's very useful but also i'm looking for an example on how to page an arraylist, i have a function that loads an arraylist from a xml file and this arraylist fills 4 flowlayoutpanels (flp) in the main form that shows 4 lists with previews of the top items for each category (images, sounds, videos and games), each flp has a limit of max items. Now i have to show two pages of items but in the same form and i don't know how to do it, if you could help me out with this i would really appreciate it.
Reply With Quote
  #8 (permalink)  
Old 09-11-09, 07:42 AM
digioz's Avatar
digioz digioz is offline
Community VIP
 
Join Date: Oct 2003
Location: Chicago, IL
Posts: 2,171
Thanks: 3
Thanked 9 Times in 9 Posts
Hello Gusadolfo,

Can you post the code that you have so far? It will make it easier to understand what you are trying to do.

Thanks,
Pete
__________________
Reply With Quote
  #9 (permalink)  
Old 09-11-09, 10:44 AM
gusadolfo gusadolfo is offline
New Member
 
Join Date: Sep 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
here's the code, the arraylist i want to page is item, it belongs to the cItems class that is an object that has a cItem class that are the arraylist which contains the items on sale, i need to page it to show it in two different pages, i hope you understood what i'm trying to do here
Code:
Private Sub mostrar()
        Dim itemsDispo As ArrayList = objCarrito.TiposDeItem
        Dim cantImagen, cantSonido, cantJuegos, cantVideos As Integer
        Dim _itemsSonidoXPagina As Integer = 8
        Dim _itemsImagenXPagina As Integer = 7
        Dim vtn As frmHomeTop = New frmHomeTop()

        Dim _indice As Integer = 0
        Dim _itemsXPagina As Integer = 10
        Dim _totalarr As Integer = 0
        Dim ini As Integer = _indice * _itemsXPagina
        Dim fin As Integer = ini + (_itemsXPagina - 1)

        vtn.MouseVisible = MouseVisible
        vtn.ModeloTelefonoNombre = My.Settings.ModeloTelefonoNombre
        vtn.ModeloTelefonoImagen = My.Settings.ModeloTelefonoImagen
        vtn.Show()
        Me.ParentForm.Close()

        objCarrito.SeleccionarDestacadoDisponibles() <--RETURNS THE AVAILABLE ITEMS

        For Each item As FrontEnd.CarritoWEB.cItem In objCarrito.Items

            Select Case item.TipoItemId
                Case 1, 10
                    If cantImagen < _itemsImagenXPagina Then
                        Dim it As ucItemImagenHm = New ucItemImagenHm(item)
                        vtn.flpImagen.Controls.Add(it)
                        cantImagen += 1
                    End If
                Case 2, 5, 11
                    If cantSonido < _itemsSonidoXPagina Then
                        Dim it As ucItemSonidoHm = New ucItemSonidoHm(item)
                        vtn.flpSonido.Controls.Add(it)
                        cantSonido += 1
                    End If
                Case 3
                    If cantJuegos < _itemsImagenXPagina Then
                        Dim it As ucItemImagenHm = New ucItemImagenHm(item)
                        vtn.flpJuegos.Controls.Add(it)
                        cantJuegos += 1
                    End If
                Case 8
                    If cantVideos < _itemsImagenXPagina Then
                        Dim it As ucItemImagenHm = New ucItemImagenHm(item)
                        vtn.flpVideos.Controls.Add(it)
                        cantVideos += 1
                    End If
            End Select
        Next

    End Sub

Last edited by Nico; 09-11-09 at 10:48 AM.
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to do sorting and paging for search function lostinsight ASP.NET 1 11-14-04 11:44 PM
C# or Vb.Net - Which is better? Pankaja Windows .NET Programming 5 11-02-04 01:21 PM
15.000+ scripts and no advanced search or sorting?!?! lee3001 General HotScripts Site Discussion 5 06-03-04 01:35 PM
Making some balls collide from an arraylist youareafatcow Everything Java 2 12-03-03 05:20 AM


All times are GMT -5. The time now is 02:15 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.