Reputation: 16040
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
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
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
Reputation: 185852
You are printing out customers
before sorting it, and you never print the sorted list. Is this what you intended?
Upvotes: 3