473,811 Members | 3,687 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting objects in ArrayList

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.
Nov 15 '05 #1
7 1824
Hi ryba,

Your objects should implement IComparable interface (easy to implement it).

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
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.

Nov 15 '05 #2
Miha and ryba,

Or, if you don't want to change the code in the object (or can't), you
can always implement the IComparer interface and then pass that interface to
the Sort method on the ArrayList.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Miha Markic" <miha at rthand com> wrote in message
news:eG******** ******@TK2MSFTN GP10.phx.gbl...
Hi ryba,

Your objects should implement IComparable interface (easy to implement it).
--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
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.


Nov 15 '05 #3
Check out my blog post about this issue:
http://weblogs.asp.net/jan/posts/6479.aspx

I'ts about how to create a generic comparer so you can easily sort objects.

--
Greetz

Jan Tielens
_______________ _______________ __
Read my weblog: http://weblogs.asp.net/jan
"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
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.

Nov 15 '05 #4
Right, I was just testing if you'll notice that I left out this option ;-)

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:OP******** ******@TK2MSFTN GP10.phx.gbl...
Miha and ryba,

Or, if you don't want to change the code in the object (or can't), you
can always implement the IComparer interface and then pass that interface to the Sort method on the ArrayList.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Miha Markic" <miha at rthand com> wrote in message
news:eG******** ******@TK2MSFTN GP10.phx.gbl...
Hi ryba,

Your objects should implement IComparable interface (easy to implement

it).

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
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.



Nov 15 '05 #5
Hi,

Please find below a class that you can use to sort a collection of any
type, the sorted type has to implement nothing.

You may use it like this:

ArrayList.Sort( new ClassSorter( "PropertyNameTo CompareBy",
SortDirection.A scending ) );
It's very simple it use reflection to get the value of
PropertyNameToC ompareBy which needs to be an IComparable.
A good thing of the shown implementation is that the property may be a
complex type and you can sort by something like:
"TopProperty.In nerProperty"

The class will see that TopProperty has a property and will descend to get
its value.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

//*************** ******** Start of the Code ************/

public class ClassSorter: IComparer

{

protected string sortBy;

protected SortDirection sortDirection;
#region Constructors

public ClassSorter(str ing sortBy, SortDirection

sortDirection)

{

this.sortBy = sortBy;

this.sortDirect ion = sortDirection;

}

#endregion

int Compare( object x, object y, string comparer)

{

if ( comparer.IndexO f( ".") != -1 )

{

//split the string

string[] parts = comparer.Split( new char[]{ '.'} );

return Compare( x.GetType().Get Property( parts[0]).GetValue(x, null) ,

y.GetType().Get Property( parts[0]).GetValue(y, null) , parts[1]

);

}

else

{

IComparable icx, icy;

icx =

(IComparable)x. GetType().GetPr operty( comparer).GetVa lue(x, null);

icy =

(IComparable)y. GetType().GetPr operty( comparer).GetVa lue(y, null);

if ( x.GetType().Get Property(compar er).PropertyTyp e ==
typeof(System.S tring) )

{

icx = (IComparable) icx.ToString(). ToUpper();

icy = (IComparable) icy.ToString(). ToUpper();

}

if(this.sortDir ection == SortDirection.D escending)

return icy.CompareTo(i cx);

else

return icx.CompareTo(i cy);

}

}
public int Compare(object x, object y)

{

return Compare( x, y, sortBy);

}
}

public enum SortDirection

{

Ascending = 0,

Descending = 1

}

//*************** ******** End of the Code ************/

"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
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.

Nov 15 '05 #6
Hi,

See my other post, I post a piece of code that implement a class that using
reflection let you sort them, all it's required is that the botton property
support IComparable.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Miha Markic" <miha at rthand com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Right, I was just testing if you'll notice that I left out this option ;-)

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in message news:OP******** ******@TK2MSFTN GP10.phx.gbl...
Miha and ryba,

Or, if you don't want to change the code in the object (or can't), you can always implement the IComparer interface and then pass that
interface to
the Sort method on the ArrayList.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Miha Markic" <miha at rthand com> wrote in message
news:eG******** ******@TK2MSFTN GP10.phx.gbl...
Hi ryba,

Your objects should implement IComparable interface (easy to implement

it).

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com

"ryba" <ba******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.tpi.pl...
> 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.
>
>



Nov 15 '05 #7
Thank you all for help...
I've implemented IComaprable interfece (Miha idea).
Nov 15 '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
1638
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?
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
25476
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
6434
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
7227
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
9726
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10647
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
10384
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
10395
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
10130
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...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4338
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3017
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.