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

  • Thread starter =?ISO-8859-1?Q?Anders_W=FCrtz?=
  • Start date
?

=?ISO-8859-1?Q?Anders_W=FCrtz?=

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
 
B

Bruce Wood

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.
 
B

Bill Butler

Bruce Wood said:
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
 
J

Jesse McGrew

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
 
B

Bruce Wood

Yes... IComparer. Serves me write for responding without first checking
the doc! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top