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 ?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With