首页 > 解决方案 > C# 如果不为 NULL,则仅分配日期时间值

问题描述

我们有一个自定义对象,我正在尝试从数据集中分配和填充。除非日期时间字段中有 NULL 值,否则它工作正常。

这是对象示例:

public class Test
{

    public DateTime Date1{ get; set; }
    public DateTime Date2{ get; set; }
 }

我们想知道如果值为空,如何最好地通过解析分配任何值:

var convertedList = (from rw in ds.Tables[0].AsEnumerable()
    select new Test()
       {
          Date1 = Convert.ToDateTime(rw?["StartDate"]),
          Date2 = Convert.ToDateTime(rw?["EndDate"])
        }).ToList();

以下内容在 null 时引发异常(应该如此)。只是想知道处理这个问题的最佳实践吗?请注意,由于外部应用程序,我们不能使用可为空的日期时间(日期时间?)。

理想情况下,如果为 null,我们不希望分配日期时间

标签: c#asp.netdatetime

解决方案


您可以检查 NULL 并替换为您想要的日期。

var convertedList = (from rw in dt2.AsEnumerable()
    select new Test()
    {
        Date1 = (rw["StartDate"] == null ? Convert.ToDateTime(rw["StartDate"]) : new DateTime()),
        Date2 = (rw["EndDate"] == null ? Convert.ToDateTime(rw["EndDate"]) : new DateTime())
    }).ToList();

推荐阅读