在数据表行中查找 min/max 日期时间

Find min/max datetime in datatable rows

我有一个数据 table,其中包含一个 "CreateDate" 和一个 "UpdateDate" 列。我试图找到最小的 CreateDate 和最大的 UpdateDate。这并不困难,但列可以包含 NULL(或 DBNull),这让我很困惑。我正在使用以下内容:

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;
}

直到我遇到了 NULL 日期行。

在继续之前先检查数据行上的值是否为空:

foreach (DataRow dr in dt.Rows)
     {
       if (dr["CreateDate"] != null && dr["UpdateDate"] != null)
         {
           //TODO: Logic here
         }
     }

您应该在将值解析为 DateTime 之前检查 DBNull.Value 和 null,因为 DateTime 日期类型不能包含空值。 请记住 DBNull.Value 和 object null 是两个不同的东西

通过声明 DateTime?、dtCreateDate、dtUpdateDate 可以包含空值。然后,如果你收到一个空值,你可以跳过它与 dtMin 和 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);

}

您可以使用数据表支持的最小和最大计算。另一种选择是使用 LINQ 查找最小值和最大值。有关参考,请参阅以下 link 的答案。 How to select min and max values of a column in a datatable?

这张地图对你有帮助

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

此处使用合并运算符和条件运算符,用于管理条件:

foreach (DataRow dr in dt.Rows)
{
    // Collecting data from DataRow
    DateTime? dtCreateDate =dr.Field<DateTime?>("CreateDate")??(DateTime?)null;
    DateTime? dtUpdateDate=dr.Field<DateTime?>("UpdateDate")??(DateTime?)null;

    // Manupulating condition to get required result
    dtMin = dtCreateDate != null ?(dtMin > dtCreateDate ? dtCreateDate : dtMin) : dtMin;
    dtMax = dtUpdateDate != null ?(dtMax > dtUpdateDate ? dtMax : dtUpdateDate): dtMax;
}