1

I'm trying to sort a list of objects depending on the return value of a method (call it Q()) in the classes that instantiate the object. Both classes Decaf and Regular derive from the same class, Coffee. The two derived classes also have different implementations of the method in question, Q(). It looks like this:

static void Main(string[] args)
{
      Decaf decafCoffee = null;
      Regular regularCoffee = null;
      List<Coffee> inventory = new List<Coffee>();
      if (type.StartsWith("D:"))
      {
          // The value of M changes based on certain criteria
          decafCoffee = new Decaf(name, D, C, M);
          inventory.Add(decafCoffee);
      }
      else if (type.StartsWith("R:"))
      {
          regularCoffee = new Regular(name, D, C, M);
          inventory.Add(regularCoffee);
      }   

      for (int j = 0; j < inventory.Count; j++)
      {
          Console.WriteLine("{0}", inventory[j].toString());
      }         
}

How can I sort this list by the value of the method Q() in the two classes in increasing order? I can post class code if need be.

2 Answers 2

3

The easiest method is probably to use Linq's OrderBy method:

var sorted = inventory.OrderBy(i => i.Q());

This will return an IEnumerable -- if you want a List just do this:

var sortedList = inventory.OrderBy(i => i.Q()).ToList();
2
  • Much faster than IComparable! Apr 26, 2013 at 4:22
  • Much less horrible than IComparable! Apr 26, 2013 at 6:03
0

Implement IComparable interface in both classes and use .Sort method.

Here is an example. http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.