471,325 Members | 1,482 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,325 software developers and data experts.

(c# .NET) sorting a list of items in a specified manner

Hi

have a list of card objects, each with a rank (1-13) and a type (hearts,
spades etc.) i would like to sort them in type order (eg. hearts before
spades) how would i go about doing that?

currently i am using an ArrayList as datastructure

i noticed the IComparable interface, can i use it to sort the array in
the specified order.

Thanks in advance

Anders
Dec 10 '05 #1
4 5355
Yes, you can. You could implement a "helper" class that implements
IComparable and then the override of Array.Sort that takes an
IComparable object as a parameter.

You could also implement IComparable in your Card class, which is OK if
you don't want any alternate sort order.

Dec 10 '05 #2

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Yes, you can. You could implement a "helper" class that implements
IComparable and then the override of Array.Sort that takes an
IComparable object as a parameter.

That would be IComparer.
Which would be the way to go if you want multiple sort orders.
You could also implement IComparable in your Card class, which is OK if
you don't want any alternate sort order.


Yup

Bill
Dec 10 '05 #3
I would implement IComparable in the card class. CompareTo() is
supposed to return a value less than 0 if this object comes before the
other, greater than 0 if this object comes after the other, or 0 if
they are equal.

The trick is to express your sort criteria as a comparison function in
such a way that it can compare any two cards: if the suits are
different, compare the suits, otherwise compare the numbers.

BTW, if you're using Visual C# 2005, you can use List<Card> and
IComparable<Card> instead of ArrayList and IComparable. That'll make
your code simpler, because you won't have to check types in the
comparison function.

Jesse

Dec 10 '05 #4
Yes... IComparer. Serves me write for responding without first checking
the doc! :-)

Dec 10 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Peter Collinson | last post: by
2 posts views Thread by Unknown User | last post: by
7 posts views Thread by David | last post: by
reply views Thread by c0mrade | last post: by
reply views Thread by rosydwin | last post: by

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.