tags:

views:

56

answers:

3

Hi I am having trouble implementing sorting on a list when DateTime is involved. I need to sort by DateTime Just put together a noddy example and I don't get the expected result. Could you see what Am I doing wrong? Thanks

   class Program
   {
       static void Main(string[] args)
       {
          List<Customer>customers=new List<Customer>();
          customers.Add(new Customer{DateOfBirth = new DateTime(2010,11,29),Name="Jo1",Surname ="Bloggs1"});
          customers.Add(new Customer { DateOfBirth = new DateTime(2010, 3, 28), Name = "Jo2", Surname = "Bloggs2" });
          customers.Add(new Customer { DateOfBirth = new DateTime(2010, 5, 29), Name = "Jo3", Surname = "Bloggs3" });
          customers.Add(new Customer { DateOfBirth = new DateTime(2010, 4, 29), Name = "Jo4", Surname = "Bloggs4" });
          customers.Add(new Customer { DateOfBirth = new DateTime(2010, 9, 29), Name = "Jo5", Surname = "Bloggs6" });

          foreach (var customer in customers)
          {
             Console.WriteLine(customer.DateOfBirth);
          }
          Console.Read();
          customers.Sort((x, y) => y.DateOfBirth.CompareTo(x.DateOfBirth));
       }
    }

    public class Customer
    {
       public string Name { get; set; }
       public string Surname { get; set; }
       public DateTime DateOfBirth { get; set; }
    }
 }
+3  A: 

You are printing out customers before sorting it, and you never print the sorted list. Is this what you intended?

Marcelo Cantos
+2  A: 

Well, that's sorting them in descending order. You could sort them in ascending order like this:

customers.Sort((x, y) => x.DateOfBirth.CompareTo(y.DateOfBirth));

If that's not what you were worried about, please specify what the problem is. Saying you don't get the expected result isn't very precise...

Jon Skeet
sorry for lame explanation now they sort in asc order.Thanks
+2  A: 

Execute Sort before Write:

      customers.Sort((x, y) => y.DateOfBirth.CompareTo(x.DateOfBirth));

      foreach (var customer in customers)
      {
         Console.WriteLine(customer.DateOfBirth);
      }
      Console.Read();
Branimir
Thanks for pointing that out.