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
object maxDate = dataTable.Compute("MAX(TheDateColumnName)", null);
object minDate = dataTable.Compute("MIN(TheDateColumnName)", null);
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();
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));
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