Reputation: 15455
Environment: Visual Studio 2008 SP1, FX3.5 The method below shows how I can sort a list by date. Is there a way to make that more generic? For example, can I make it accept a string list or a date list and then sort. I was thinking maybe use DateTime.TryParse and if it's a date then list is a date then sort by DateTime, otherwise it's a list of string and sort by that instead.
public class Helpers
{
public static List<DateTime> SortAscending(List<DateTime> list)
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}
public static List<DateTime> SortDescending(List<DateTime> list)
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}
}
Upvotes: 1
Views: 96
Reputation: 245429
Your method could easily be changed to:
public static List<T> SortAscending(List<T> list) where T : IComparable
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}
public static List<T> SortDescending(List<T> list) where T : IComparable
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}
Which will allow you to sort a List of any type that implements IComparable
.
Upvotes: 5