c# - 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,我们不希望分配日期时间
解决方案
您可以检查 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();
推荐阅读
- google-drive-api - 如何从 google drive api 获取资源密钥
- python - 可以抓取标签内所有数据的正则表达式
- github - 从 Jenkins Job 将更改推送到 Github
- ocaml - OCaml 流水线和类型构造函数参数
- flutter - valuenotifier 在更新列表时未更新小部件
- git - 您可以将现有的 git 存储库转换为“blobless”吗?
- google-apps-script - 如何根据自动过滤数据动态传输所有 Google 表格中的数据
- docker - 如何在 dockerfile 中为我的服务找到我需要的基本映像
- postcss - PostCSS 插件的未知错误。您当前的 PostCSS 版本是 8.3.0,但 postcss-preset-env 使用 7.0.36
- rust - 如何捕捉anyhow::Result?