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")}};


Currently rated 2.0 by 6 people

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



Enterprise Administrator certification

by Sander Gerz December 06, 2008 10:12
Windows Server 2008 De Basis

This came in my mail this morning: "Congratulations on earning your Enterprise Administrator certification! We hope you enjoy the benefits of your certification and of membership in the Microsoft Certified Professional community."

 Last Wednesday was my final exam: “70-647 PRO: Windows Server 2008, Enterprise Administrator”. Although the score was good (947) it felt like the most difficult exam of the five. With all those trees and forests, it was not a walk in the park.

Just in time for my book which is now published.

Currently rated 2.3 by 3 people

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


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