C# – How to sort ArrayList of DateTime objects in descending order
c++
How do I sort ArrayList of DateTime objects in descending order?
Thank you.
Best Solution
First of all, unless you are stuck with using framework 1.1, you should not be using an ArrayList at all. You should use a strongly typed generic List<DateTime> instead.
For custom sorting there is an overload of the Sort method that takes a comparer. By reversing the regular comparison you get a sort in descending order:
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);
var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead, you could also include StartsWith clause as well.
Best Solution
First of all, unless you are stuck with using framework 1.1, you should not be using an
ArrayList
at all. You should use a strongly typed genericList<DateTime>
instead.For custom sorting there is an overload of the
Sort
method that takes a comparer. By reversing the regular comparison you get a sort in descending order:Update:
With lambda expressions in C# 3, the delegate is easier to create: