简体   繁体   English

C# 如果不是 NULL,则仅分配日期时间值

[英]C# Only assign a datetime value if not NULL

We have a custom object that i'm trying to assign and populate from a dataset.我们有一个自定义对象,我试图从数据集中分配和填充它。 It works fine unless there is a NULL value in the datetime fields.除非日期时间字段中存在 NULL 值,否则它可以正常工作。

here is the object example:这是对象示例:

public class Test
{

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

We are wondering how best to byparse assigning any value if the value is null:我们想知道如果值为 null 时如何最好地通过解析分配任何值:

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

The following throws an exception (as it should) when null.当为空时,以下内容会引发异常(应该如此)。 Just wondering the best practice to handle this?只是想知道处理这个问题的最佳实践? Note we cannot use a nullable datetime (datetime?) due to an external app.请注意,由于外部应用程序,我们不能使用可为空的日期时间(日期时间?)。

Idealy, we would not want to assign the datetime if null理想情况下,如果为空,我们不希望分配日期时间

You may want to Assign some default value like:您可能希望分配一些默认值,例如:

Date1 = rw?["StartDate"]==null?DateTime.MinValue:Convert.ToDateTime(rw?["StartDate"]);

Or just ignore those with null values:或者只是忽略那些具有空值的:

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

You can check for NULL and replace with a date you want.您可以检查 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();

你能不能不使用 DateTime.TryParse,它会尝试将字符串转换为 dateTime,但如果不能,它将使用 dateTime.minValue?

Are you going for sanity checks on inputted values?您是否要对输入的值进行完整性检查? If so, what I call "Passive Error Reporting" might be the way.如果是这样,我所说的“被动错误报告”可能就是这样。

INotifyDataErrorInfo is all about telling the user about issues - and allowing you to check of there are no errors before comitting - without "resorting" to Exceptions. INotifyDataErrorInfo就是告诉用户有关问题的全部内容 - 并允许您在提交之前检查没有错误 - 无需“求助于”异常。

You use it often in WPF where the ViewModel might be required to be accept nullable values or even strings for Numbers (for entirely view reason), but the Model can not accept Null values or anything but parsed Integers.您经常在 WPF 中使用它,其中 ViewModel 可能需要接受可空值甚至数字字符串(完全出于视图原因),但模型不能接受 Null 值或除解析的整数之外的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM