Skip to content
Article

Using .NET 3.5 and Reflection to help with sorting a List

The other day I was looking to be able to sort a list of products (List<Product>).  I was binding that list to a ListView and the client wanted to be able to sort the Products by Name (Z-A & A-Z) and by Price (Low-High and High-Low).

I initially had something like this:

public class SortProductsByPrice : IComparer
{
  public int Compare(Product Prod1, Product Prod2)
  {
    return Prod1.Price.CompareTo(Prod2.Price);
  }
}

That works, but I didn’t want to write a class for everything I wanted to be able to sort by. For what the client wanted above I would have had to write 4 different classes.

So I set off looking for an awesome way to write one sort method. Sparing you the endless results of clicking through many search results and articles, I ran across a couple things caught my attention: .Net Reflection, hey look I can see myself! and How to sort a ListView control by a column in Visual C#.

Combining ideas from both of those examples above I produced a class that will Sort a List of any objects.

public class Sort : IComparer
{
  // Specifies the Property to be sorted
  public String SortBy { get; set; }

  // Specifies the order in which to sort (i.e. 'Ascending').
  public SortDirection OrderOfSort { get; set; }

  public Sort(String SortBy, SortDirection OrderOfSort)
  {
    this.SortBy = SortBy;
    this.OrderOfSort = OrderOfSort;
  }

  public int Compare(T x, T y)
  {
    int compareResult;

    Type MyTypeObject = typeof(T);

    PropertyInfo prop = MyTypeObject.GetProperty(SortBy);

    if (prop == null)
    {
      return 0;
    }

    switch (prop.PropertyType.Name)
    {
      case "String":
        compareResult = prop.GetValue(x, null).ToString().CompareTo(
          prop.GetValue(y, null).ToString());
        break;
      case "DateTime":
        compareResult = Convert.ToDateTime(prop.GetValue(x, null)).CompareTo(
          Convert.ToDateTime(prop.GetValue(y, null)));
        break;
      case "Double":
        compareResult = Convert.ToDouble(prop.GetValue(x, null)).CompareTo(
          Convert.ToDouble(prop.GetValue(y, null)));
        break;
      default:
        compareResult = 0;
        break;
    }

    switch (OrderOfSort)
    {
      case SortDirection.Ascending:
        return compareResult;
      case SortDirection.Descending:
        return (-compareResult);
      default:
        return 0;
    }
  }
}

Now I can utilize this awesome new class by calling it like this:

ProductList.Sort("Price", SortDirection.Ascending);

The concept here is you just pass the property you want to sort by (i.e. Price) and the direction and “Bam” (as Emeril says)!

The next step here would just be to add some additional cases to my switch statement to check for other DataTypes (like Decimal, Int, etc).

The Atlantic BT Manifesto

The Ultimate Guide To Planning A Complex Web Project

Insights

Atlantic BT's Insights

We’re sharing the latest concepts in tech, design, and software development. Learn more about our findings.

Questions & Answers

What is the best web development framework?
Many people commonly ask “what is a framework in web development?” Web development frameworks can easily be confused with web development tools, languages, or parts of the web development stack (like .NET, PHP, JavaScript, or Ruby).
Learn More about What is the best web development framework?
What is the best programming language for web development?
If there was one “best” programming language, then everything else would be obsolete. The reality is that there are so many different programming languages because there is no “best” language for any situation.
Learn More about What is the best programming language for web development?
How much does web development cost?
Web development can vary from a few hundred to millions of dollars depending on what is needed. You may simply need some changes to something that already exists, or you'd like to build a large or complex application.
Learn More about How much does web development cost?
What is PHP web development?
PHP is a back end language primarily used for custom applications, content management systems (such as Wordpress), eCommerce engines (such as Magento), or even massive sites like Facebook.
Learn More about What is PHP web development?
What is the best way to become a web developer?
We get lots of questions from university students working on projects -- How do I get into web development? How long does it take to learn? How much do web developers make?
Learn More about What is the best way to become a web developer?
What is front end vs. back end development?
As web development evolved, it separated into logical specialization: front end web development and back end development. While back end development involves the server-side development, front end is the final rendering.
Learn More about What is front end vs. back end development?
What is full stack web development?
Full stack web development as a term evolved due to the separation of roles between front end and back end developers. A “full stack” developer is a developer that can work in both front end and back end technologies.
Learn More about What is full stack web development?