Search code examples
c#datatableminmax

Find min/max datetime in datatable rows


I have a data table that contains a "CreateDate" and an "UpdateDate" columns. I am trying to find the smallest CreateDate and largest UpdateDate. It is not difficult but columns can contain NULL (or DBNull) and this is tripping me. I was using the following:

DateTime dtMin = DateTime.MaxValue;
DateTime dtMax = DateTime.MinValue;

foreach(DataRow dr in dt.Rows)
{
    DateTime dtCreateDate = dr.Field<DateTime>("CreateDate");
    DateTime dtUpdateDate = dr.Field<DateTime>("UpdateDate");
    dtMin = dtMin > dtCreateDate ? dtCreateDate : dtMin;
    dtMax = dtMax > dtUpdateDate ? dtMax : dtUpdateDate;
}

Until I hit a row with a NULL date.


Solution

  • You should to check DBNull.Value and null before you parse values to DateTime because DateTime datetype cannot contain null values. Remember that DBNull.Value and object null are 2 different things

    By declaring DateTime?, dtCreateDate, dtUpdateDate can contain null value. Then, if you receive a null value, you can skip to compare it with dtMin and dtMax.

    foreach (DataRow dr in dt.Rows)
    {
        DateTime? dtCreateDate = dr["CreateDate"] == DBNull.Value || dr["CreateDate"] == null ? (DateTime?) null : dr.Field<DateTime>("CreateDate");
        DateTime? dtUpdateDate = dr["UpdateDate"] == DBNull.Value || dr["UpdateDate"] == null ? (DateTime?) null: dr.Field<DateTime>("UpdateDate");
    
    
        dtMin = dtCreateDate == null ? dtMin : (dtMin > dtCreateDate ? dtCreateDate : dtMin);
        dtMax = dtUpdateDate == null ? dtMax : (dtMax > dtUpdateDate ? dtMax : dtUpdateDate);
    
    }