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

Can you integrate with my existing systems and teams?

Yes, both technically and operationally. On the technical side, our engineering heritage allows us to connect modern cloud, data, and AI capabilities securely to your existing ERPs, CRMs, and proprietary software using SOC 2 Type 2 certified practices. On the operational side, we never work in a silo. Our senior architects embed directly with your in-house developers and stakeholders, aligning with your governance protocols and building internal capability so your team can confidently maintain and scale the system.

Learn More about Can you integrate with my existing systems and teams?
Why should we pay for a discovery phase when we can jump straight into development?

Investing in a strategy and discovery phase prevents costly rework, scope creep, and misaligned features before your engineering budget is committed to full-scale development. While jumping straight into writing code can feel faster at the beginning, uncovering hidden legacy bottlenecks, unclear user requirements, or integration roadblocks midway through a build is significantly more expensive to fix in production than on paper.

A structured discovery phase protects your budget and timeline in four practical ways:

  • Validates Assumptions Before Engineering Begins: Through stakeholder interviews, workflow observations, and a clickable prototype, your team can test user flows and gather real feedback early so we can ensure we build the exact features your business needs.
  • Uncovers Hidden Technical Constraints: Auditing your existing databases, APIs, and security requirements upfront reveals integration hurdles and technical debt before developers write a single line of production code.
  • Produces Accurate Budgets & Timelines: Defining clear technical requirements and architecture blueprints eliminates guesswork, giving leadership reliable cost estimates and realistic delivery milestones.
  • Aligns Leadership & Technical Teams: Getting executive sponsors, end users, and IT stakeholders on the same page early prevents mid-project priority shifts that stall momentum and inflate costs.

Learn More about Why should we pay for a discovery phase when we can jump straight into development?
What does my business get by the end of a technology consulting engagement?

At the end of a technology consulting engagement with Atlantic BT, your business walks away with a clear, actionable blueprint and a validated prototype so your leadership team can move into development with full confidence. Rather than leaving you with high-level theory, our senior architects deliver concrete artifacts built around your actual operations:

  • Stakeholder & Workflow Findings: Insights gathered from executive stakeholder interviews and hands-on contextual inquiries that map out how your teams currently work and where daily bottlenecks occur.
  • Comprehensive Systems Audit: A technical evaluation of your existing software stack, databases, integrations, and security posture to pinpoint technical debt and modernization opportunities.
  • Prioritized Recommendations & Roadmap: An objective, vendor-agnostic plan outlining which software, cloud, or AI solutions will deliver the highest return on investment, complete with scope, timeline, and budget estimates.
  • Fully Clickable Prototype: If building software, an interactive front-end prototype that lets your team test user flows, validate assumptions, and gather real feedback before investing in full-scale engineering.

Learn More about What does my business get by the end of a technology consulting engagement?
What does enterprise technology consulting cost for businesses?

A focused enterprise AI readiness assessment and strategy roadmap typically ranges from $10,000 to $75,000, depending on the complexity of your data infrastructure, security requirements, and the number of workflows evaluated. At Atlantic BT, we scope engagements transparently around defined deliverables, such as a systems audit, prioritized ROI roadmap, and working prototype, so you can validate business value before committing to full-scale development. 

Our initial AI strategy discovery process starts at $10,000 and includes evaluation of 3 workflows and initial suggestions.

Learn More about What does enterprise technology consulting cost for businesses?