Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the max in a datacolumn of datetime?

I have a DataColumn of DateTime, I would like to know how I can have only the sooner date (min) and the later date (max).

Thanks

like image 799
francops henri Avatar asked Nov 28 '11 16:11

francops henri


3 Answers

object maxDate = dataTable.Compute("MAX(TheDateColumnName)", null);
object minDate = dataTable.Compute("MIN(TheDateColumnName)", null);
like image 146
Fergara Avatar answered Nov 15 '22 03:11

Fergara


This would give what you are looking for:

// Initial Code for Testing
DataTable dt = new DataTable();

dt.Columns.Add("Dates", typeof(DateTime));
dt.Rows.Add(new object[] { DateTime.Now });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(1) });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(2) });

This is the code you would use:

// Actual Code
DataColumn col = dt.Columns[0]; // Call this the one you have

DataTable tbl = col.Table;

var first = tbl.AsEnumerable()
               .Select(cols => cols.Field<DateTime>(col.ColumnName))
               .OrderBy(p => p.Ticks)
               .FirstOrDefault();

var last = tbl.AsEnumerable()
              .Select(cols => cols.Field<DateTime>(col.ColumnName))
              .OrderByDescending(p => p.Ticks)
              .FirstOrDefault();
like image 30
Kyle Rosendo Avatar answered Nov 15 '22 04:11

Kyle Rosendo


To add to the answer from kyle, isn't it easier to just do:

for greatest date:

var last = tbl.AsEnumerable()
               .Max(r => r.Field<DateTime>(col.ColumnName));

and for earliestdate:

var first = tbl.AsEnumerable()
               .Min(r => r.Field<DateTime>(col.ColumnName));
like image 25
MichelZ Avatar answered Nov 15 '22 04:11

MichelZ