简体   繁体   中英

Minimum and maximum data form Data Table

I have data Table with four columns: Date , isin , Price and State .
I need to get minimum and maximum date from the Date column.
I'm using this code and it works fine with one file however with other file it shows me wrong maximum date.

 DateTime stDate = Convert.ToDateTime((excleTable.Compute("min(date)", string.Empty)));
 DateTime eDate = Convert.ToDateTime((excleTable.Compute("max(date)", string.Empty)));

For example on first row i have 02/27/2015 and on last row i have 03/31/2015 but it reads only till 03/09/2015 which is incorrect.
Any ideas what should i do ?

Looks like your column type isn't DateTime . If you can fix that than make sure that your DataTable has DateTime type for column date , otherwise you can use LINQ's Max and Min and convert your column to DateTime like:

DateTime stDate =  dt.AsEnumerable()
                     .Max(r => Convert.ToDateTime(r.Field<string>("date")));

DateTime eDate =  dt.AsEnumerable()
                     .Min(r => Convert.ToDateTime(r.Field<string>("date")));

You may have to use DateTime.ParseExact for converting to DateTime , if your string values doesn't correspond to default/available DateTime formats, like:

DateTime stDate =  dt.AsEnumerable()
    .Max(r => DateTime.ParseExact(r.Field<string>("date"), 
                                    "MM/dd/yyyy", 
                                    CultureInfo.InvariantCulture)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM