English 中文(简体)
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 ?

最佳回答

I like the simple solution.

DateTime minDate = DateTime.MaxValue;
DateTime maxDate = DateTime.MinValue;
foreach (string dateString in StringDates)
{
    DateTime date = DateTime.Parse(dateString);
    if (date < minDate)
        minDate = date;
    if (date > maxDate)
        maxDate = date;
}
问题回答

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));

Via Linq, you can do:

from row in StringDates
group row by true into r 
select new { 
    min = r.Min(z => z), 
    max = r.Max(z => z) 
}

This is similar to @Jeffrey s answer, but instead of parsing each date, it first finds the min and max dates comparing its string values, and then it parses the values at the end.

// This method handles the date comparisons
private int WeirdComparer(string strDate1, string strDate2)
{
    int res = string.Compare(strDate1, 6, strDate2, 6, 4);
    if (res == 0)
        res = string.Compare(strDate1, 3, strDate2, 3, 2);
    if (res == 0)
        res = string.Compare(strDate1, 0, strDate2, 0, 2);
    return res;
}

public void FindMinAndMaxDates(IList<string> strDates, out DateTime minDate, out DateTime maxDate)
{
    string min = "99.99.9999";
    string max = "00.00.0000";
    foreach (string strDate in strDates)
    {
        if (WeirdComparer(strDate, min) < 0)
            min = strDate;
        if (WeirdComparer(strDate, max) > 0)
            max = strDate;
    }
    minDate = DateTime.ParseExact(min, "dd.MM.yyyy", null);
    maxDate = DateTime.ParseExact(max, "dd.MM.yyyy", null);
}

I know this isn t a direct answer to your question, but could help others if they come here looking for something similar.

I ran across this issue today while trying to find just the max date from a list of objects. Sometimes there won t be a value in the date for the objects so I had to figure out how to use a try parse with my linq.

From a combination of what Mark used here I came up with this to solve my problem

        List<string> stringDates = new List<string>();
        stringDates.Add("Not a date");
        stringDates.Add("2015-01-01");
        stringDates.Add("2015-10-10");
        stringDates.Add("2015-9-10");
        stringDates.Add("123");

        DateTime sapInvoiceDate;
        DateTime tempDate = DateTime.MinValue;
        sapInvoiceDate = stringDates.Select(x => DateTime.TryParse(x, out tempDate)).Select(x => tempDate).Max();  




相关问题
Mysql compaire two dates from datetime?

I was try to measure what is faster and what should be the best way to compare two dates, from datetime record in MySql db. There are several approaches how to grab a date from date time, but I was ...

iPhone Date Picker rolls over to 2010 on December 27th?

So I implemented a UIDatepicker in one of my applications for scheduling and autodialing teleconferences... everything is pretty much ready to go except, while testing I noticed that when the date ...

Convert date Python

I have MMDDYY dates, i.e. today is 111609 How do I convert this to 11/16/2009, in Python?

specifying date format when using $form->inputs() in CakePHP

I am wondering if there is a way to specify the date format in the forms created using CakePHP s $form->inputs(); Please note that this is not the individual $form->input() but instead $form->inputs() ...

NSDateFormat, super simple! Where am I screwing up?

Ok, this is really simple, maybe I m a getting a bit burnt out, but seems like it should work, Query XML feed, put out date string, format, display in a cell. The issue is I m a getting a NULL ...

sqlite writing a date into an email

I am exporting a date value from sqlite and placing it into an email. The date appears like this 279498721.322872 I am using Objective C in an Iphone App. Does anyone know how to make this export ...

热门标签