Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Calculate min date / max date from a List

I have a List which contains Dates :

List<string> StringDates;

    [0]: "04.03.2010"
    [1]: "09.03.2010"
    [2]: "11.03.2010"
    [3]: "12.03.2010"
    [4]: "16.03.2010"
    [5]: "18.03.2010"
    [6]: "19.03.2010"
    [7]: "23.03.2010"
    [8]: "25.03.2010"
    [9]: "26.03.2010"

Using C# what is the best/shortest way to find out min date / max date from this list ?

like image 946
Murtaza Mandvi Avatar asked Feb 25 '10 21:02

Murtaza Mandvi


2 Answers

Convert them to DateTime using ParseExact (or TryParseExact) and then use Linq to get the Min and Max:

List<DateTime> dates = StringDates
   .Select(x => DateTime.ParseExact(x, "dd.MM.yyyy", null))
   .ToList();
DateTime minDate = dates.Min();
DateTime maxDate = dates.Max();

Note that in your example the list was already sorted in ascending order. If you can guarantee that this will always be the case and you want better performance, you could just take the first and last element which would be O(1) instead of O(n). But the above is safer so even if your listed probably will always be sorted, you probably shouldn't make this optimization unless you actually need it, just in case one day the list doesn't come in sorted order.

like image 165
Mark Byers Avatar answered Nov 14 '22 01:11

Mark Byers


use linq!:

    var list = new List<DateTime>();
    list.Add(new DateTime(2010, 1, 1));
    list.Add(new DateTime(2008, 1, 1));
    list.Add(new DateTime(2009, 1, 1));
    Console.WriteLine(list.Max(date => date));
    Console.WriteLine(list.Min(date => date));
like image 27
Ryan Ferretti Avatar answered Nov 14 '22 01:11

Ryan Ferretti