Skip to content

Sorting classes in a list

cakewalkr7

Asked Mar 31, 2007, 1:34 PM EDT1 answer
Share
LinkedInX
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.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Read up on the IComparable interface.

    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.
      }
    }
    0