user9969
user9969

Reputation: 16040

Sorting a List<T> by DateTime

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

Upvotes: 0

Views: 625

Answers (3)

Branimir
Branimir

Reputation: 4367

Execute Sort before Write:

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

      foreach (var customer in customers)
      {
         Console.WriteLine(customer.DateOfBirth);
      }
      Console.Read();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500515

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...

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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

Upvotes: 3

Related Questions