Sorting generic lists; can it be done with less code?

by Sander Gerz December 15, 2008 09:42

Trying to find a method to sort a generic list, I found this solution. While this seems like an elegant solution, I found it a bit much code for my purpose. I only wanted to sort a list with objects that had a date property. This is the shortest version I could come up with (C# 3.0):

list.Sort((p1, p2) => p1.DateAdded.CompareTo(p2.DateAdded));

Obviously, sorting on any other property is just as simple:

list.Sort((p1, p2) => p1.ProductName.CompareTo(p2.ProductName));

Here's the class definition and some sample data to do the exercise yourself if you want to.

    class Product

    {

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal Price { get; set; }

        public DateTime DateAdded { get; set; }

    }

       List<Product> list = new List<Product>() {

            new Product() {ProductId=1, ProductName="Item1",

                Price=20.00M, DateAdded=DateTime.Parse("2008-11-02")},

            new Product() {ProductId=1, ProductName="Item2",

                Price=10.00M, DateAdded=DateTime.Parse("2008-04-02")},

            new Product() {ProductId=1, ProductName="Item3",

                Price=40.00M, DateAdded=DateTime.Parse("2008-02-03")},

            new Product() {ProductId=1, ProductName="Item4",

                Price=30.00M, DateAdded=DateTime.Parse("2008-11-01")}};

Enjoy.

Currently rated 2.0 by 6 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant