Search code examples
c#datetimemaxdatacolumn

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


Solution

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