I have a problem.
I have an ArrayList of objects. Each object contains a DateTime data field.
I need to sort this ArrayList by this DateTime data field.
This is my current code and it does not work:
for (int i = 0;i<EventHolder.Count;i++)
{
Event obj = (Event) EventHolder[i];
try
{
obj2=(Event)EventHolder[i+1];
}
catch
{
break;
}
DateTime date1 = DateTime.ParseExact(obj.Date_And_Time,"dd/MM/yyyy HH:mm",region);
DateTime date2 = DateTime.ParseExact(obj2.Date_And_Time, "dd/MM/yyyy HH:mm", region);
if (DateTime.Compare(date1,date2)>0)
{
Event tempobj=obj2;
EventHolder[i+1]=obj;
EventHolder[i]=tempobj;
}
}
foreach (Event i in EventHolder)
{
Console.WriteLine(i.Date_And_Time);
}
Console.ReadLine();
I use these 3 dates to test if it works:
23/11/2011 12:15
28/06/2010 04:05
02/09/1992 03:54
The output is always:
28/06/2010 04:05
02/09/1992 03:54
23/11/2011 12:15
I tried using just > and < operators for comparing and got same results. I also tried using different commands to convert the strings to DateTime objects, like Convert.ToDateTime, DateTime.Parse. Tried entering without HH:mm (adjusted the code accordingly) and still had the same output. I tried not using IFormatProvider (set it to null) and got nowhere again.
By chance, I found this thread:
How to sort ArrayList of DateTime objects in descending order?
I extracted all the dates from the objects and put them into this DateTime list. Used List.Sort() and it produced correct output. But then I got stuck at how to use this sorted list to sort my EventHolder ArrayList. I’ve been banging on this wall for a while, and produced no result.
I am very new to programming, so I hardly know any good way of doing what I’m doing. And it doesn’t even work.
Can anybody explain to me where I’m going wrong?
What you’re trying to do there is implement a sorting algorithm but unfortunately yours is not a correct one. It almost looks like Bubble Sort which is a pretty slow algorithm to begin with but it’s not quite correct.
A much better way to accomplish what you’re trying to do is to use the Sort method or ArrayList or of the generic List<> classes. Those sort methods allow you to provide an IComparer implementation (or a comparison delegate in the case of the generic List) to specify the sort criteria and internally they use a correct and efficient sort algorithm.
If you use the generic List<> you could just pass in a lambda expression and have it dictate the sorting criteria based on the date field, like so: