sorting classes in a list
I have a list of classes I created and I want to sort that list by one field in the class. I've tried following examples, but they're all examples of sorting a list of strings or ints so I'm not sure how to sort my list of classes by a field in the class. My class is a storeitem class and I want to sort it by the manufacturer field. Can anyone give me an idea how to do this? Thanks.
SokakPosted Apr 3, 2007, 1:09 AM
The CompareTo method will accept an "Object" as parameter, you will need to validate that it is comparing to the type you want to compare. (obj is StoreItem) then you can compare your desired fields.
For instance: (Not gauranteed to compile, but should give you an idea.)
public class StoreItem : IComparable
{
private int _manufacturerID;
int IComparable.Compare(object obj)
{
if ( obj is StoreItem )
{
return _manufacturerID.CompareTo( ((StoreItem)obj)._manufacturerID );
}
// else throw a suitable exception.
}
}