473,837 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting an ArrayList of Objects

Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074
Nov 21 '05 #1
7 1356
This should get you started using the IComparer Interface
http://www.asp.net/TimeTrackerStarte...tion.vb&rows=1
"Derek Martin" <dm*****@DONTSP AMMEokstateDOT. edu> wrote in message
news:uQ******** ******@TK2MSFTN GP12.phx.gbl...
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the
values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074

Nov 21 '05 #2
Derek,

Why you want only the arraylist while there are so many other
ilist/icontainer classes that does it direct, I said last time the
datatable, however there is as well the hashtable or maybe even better the
sortedlist.

Otherwise you are doing something what everybody else sees no need to, so
why take effort in that.
However there can be someone who want to help you to make what is done in
another way. However when not don't set here that you did not got an answer.

http://msdn.microsoft.com/library/de...classtopic.asp

However I hope this helps anyway?

Cor

"Derek Martin" <dm*****@DONTSP AMMEokstateDOT. edu> schreef in bericht
news:uQ******** ******@TK2MSFTN GP12.phx.gbl...
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the
values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074

Nov 21 '05 #3

"Derek Martin" <dm*****@DONTSP AMMEokstateDOT. edu> wrote
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the values
of one of the object's members. <...> I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Add a button to a new form and paste in the code below, see if that can
get you started on using the IComparer interface....

HTH
LFS
Private Structure MyData
Public Name As String
Public Age As Short

Public Sub New(ByVal Name As String, ByVal Age As Short)
Me.Name = Name
Me.Age = Age
End Sub
End Structure
Private Class NameSorter
Implements IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collecti ons.IComparer.C ompare
Return New CaseInsensitive Comparer().Comp are( _
DirectCast(x, MyData).Name, _
DirectCast(y, MyData).Name)
End Function
End Class

Private Class AgeSorter
Implements IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collecti ons.IComparer.C ompare
Return DirectCast(x, MyData).Age.Com pareTo(DirectCa st(y, MyData).Age)
End Function
End Class
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) _
Handles Button1.Click

Dim text As MyData
Dim data() As MyData
data = New MyData() {New MyData("Joe", 10), New MyData("Sue", 12), _
New MyData("Bob", 16), New MyData("Sam", 8)}
Console.WriteLi ne(vbCrLf & "Raw data:")
For Each text In data
Console.WriteLi ne(text.Name & " " & text.Age)
Next

Console.WriteLi ne(vbCrLf & "By Name:")
Array.Sort(data , New NameSorter)
For Each text In data
Console.WriteLi ne(text.Name & " " & text.Age)
Next

Console.WriteLi ne(vbCrLf & "By Age")
Array.Sort(data , New AgeSorter)
For Each text In data
Console.WriteLi ne(text.Name & " " & text.Age)
Next

End Sub

Nov 21 '05 #4
The below code is for an array named Rows of classes where each element of
the array is an object of "myClass" type. Note that "myProperty " is the
"myClass" Property that you want to sort on. SortOrder True is for ascending
and CaseSensitive is true if you want a sort that is case sensitive. Hope
this helps.
Dim mycomparer As mycompare = New mycompare(SortO rder, CaseSensitive)
Array.Sort(Rows , mycomparer)

Public Class mycompare
Implements IComparer
Private m_ascending As Boolean
Private ci As CultureInfo = New CultureInfo("")
Private v_CaseSensitive As Boolean
Public Sub New(ByVal ascending As Boolean, ByVal valuetype As Type, ByVal
CaseSensitive As Boolean)
m_ascending = ascending
v_CaseSensitive = CaseSensitive
End Sub

Private Function Compare(ByVal x As Object, ByVal y As Object) As Integer
_ Implements IComparer.Compa re
x = DirectCast(x, myClass).MyProp erty
y = DirectCast(y, myClass).MyProp erty
If m_ascending Then
If Not v_CaseSensitive Then Return New CaseInsensitive Comparer
_().Compare(x, y) Else Return New Comparer(ci).Co mpare(x, y)
Else
If Not v_CaseSensitive Then Return New CaseInsensitive Comparer
_().Compare (y, x) Else Return New Comparer(ci).Co mpare(y, x)
End If

End Class

"Derek Martin" wrote:
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074

Nov 21 '05 #5
Note that in the previous example I sent you, if X or Y object value is
DBnull, it will fail. I actually have a try/catch around the .compare method
where I catch any x.GetType.Name = "DBNull" and set it to whatever data type
value would be equal to Null such as string would be "". Good Luck

"Derek Martin" wrote:
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074

Nov 21 '05 #6
"Derek Martin" <dm*****@DONTSP AMMEokstateDOT. edu> schrieb:
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the
values
of one of the object's members.


CompareOperator
<URL:http://dotnet.mvps.org/dotnet/samples/codingtechnique/CompareOperator .zip>

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 21 '05 #7
Thank you all so much! I will take a peak at all of these wonderful
suggestions as soon as I get unstuffed from the Pre-Pre-Christmas dinner!

Derek

"Derek Martin" <dm*****@DONTSP AMMEokstateDOT. edu> wrote in message
news:uQ******** ******@TK2MSFTN GP12.phx.gbl...
Hi there, I've asked before but never got an answer that could get me
completely to where I was heading. I have an arraylist that contains
defined objects and I would like to sort this arraylist based on the
values
of one of the object's members.

Here is a bit of code to illustrate my setup:

Object construction and insertion:
Dim entity As New entityobjects(e ntitynamenodeli st(i).InnerXml,
typenodelist(i) .InnerXml, ...)
entityarraylist .add(entity)
----------------------------------------------------------------------------------------------
Object definition class:
Public Class entityobjects
Protected m_entityid As String
Protected m_entityname As String
Protected m_type As String
...

Public Sub New(ByVal entityname As String, ByVal type As String ...)
Me.entityname = entityname
Me.type = type
...
End Sub
----------------------------------------------------------------------------------------------

Now, I would like to list out the objects sorted by entityname:

'What can I put here to sort these???

for each entity as object in entityarraylist
richtextbox1.ap pendtext(entity .toString()) 'toString is overridden here
in the object class
next
----------------------------------------------------------------------------------------------

I have read that I can implement icomparable or icomparer in the object
class but can't quite put my finger on how?

Thank you!
Derek
--
Derek Martin
593074

Nov 21 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
322
by: Nick | last post by:
Hi ! I have Objects in my ArrayList These Objects contain a String called "Name". And i want that ArrayList to sort it's objects using the Name element of each object and not something else of the object ?!? I think this is somehow accomplished using the Comparer class, but i have not checked it out yet.
1
1640
by: Daniel | last post by:
does C# have any collection objects that support sort functionality so that I dont have to write my own sorting algorithm?
7
1826
by: ryba | last post by:
Hello I'm sorry for mistakes - my English isn't very well. I've got the problem with sorting objects in ArrayList. If I put there only strings, Sort method works great, but it doesnt work when I put there objects (even if ToString method is override in object class). I think that i have to override a comparator in my object class, but even if it is correc I dont know how to do it... I'd be very greatfull if Somebody could help me.
6
8191
by: Bryon | last post by:
I need to sort an ArrayList of objects. I am unable to find a method for this. DO I need to role my own sorting? Or is there something like the qsort() function in C of old??? Thanks
2
5077
by: Rob G | last post by:
Hello, I have a basic understanding of Objects, inheritance, polymorhpism, etc. I am new to VB.NET and I am having a problem figuring this out. I want to sort a CheckBoxList. Using the ArrayList seemed to make the most sense. When I use it I get the error: At least one object must implement IComparable. Here's the code that produces that error: Public Class Sorting
19
25482
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to sort columns based on the column header the user has clicked in both Ascending and Descending formats.
16
6435
by: RCS | last post by:
So I have an ArrayList that gets populated with objects like: myAL.Add(new CustomObject(parm1,parm2)); I'm consuming this ArrayList from an ObjectDataSource and would like to have this support sorting (because it's ultimately being consumed in a GridView). I can't simply sort the ArrayList (because it only knows it's holding a bunch of objects). So I need a way to sort the ArrayList, based on the data - that is within the objects that...
2
4731
by: Rob Meade | last post by:
Dear all, I have a class which contains an arraylist populated with other objects, for example: PrescriptionQueue - containing multiple instances of Prescription I have the need on my web page to display this data which I have done, however, now I would like to sort it based on a data item/direction selected by the user from the web page.
6
7229
by: Arthur Dent | last post by:
How do you sort a generic collection derived from System.Collections.ObjectModel.Collection? Thanks in advance, - Arthur Dent
0
1279
by: planb | last post by:
Hello, I am working with a class with a basetype of NameObjectCollection, which has as a member an object array public object Objects {get {return BaseGetAllValues();}} which I want to sort before using.... I know I can do do a rough quivalent by feeding that into a new ArrayList and then sorting the array list and using it, but is there a
0
10874
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10566
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10623
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10271
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7806
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5668
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4040
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3124
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.