处理DateTime

时间:2017-05-31 11:46:08

标签: c# datetime collections

我正在将DataTable转换为通用List,因为我正在将行值转换为列表的对象,它会给出Cast Exception。我已经尝试使用代码

处理DBNull
if (dataRow["DateCompleted"] == DBNull.Value)
{
    dataRow["DateCompleted"] = null;
}
if (dataRow["TotalRecords"] == DBNull.Value)
{
    dataRow["TotalRecords"] = 0;
}
if (dataRow["CompanyName"] == DBNull.Value)
{
    dataRow["CompanyName"] = "";
}

但DateCompleted不接受null,DBNull或空字符串。

在这个过程之后,我正在制作像

这样的对象
DemoData demoValue = new DemoData
{
    CompanyName = dataRow["CompanyName"].ToString(),
    DateCompleted = (DateTime)dataRow["DateCompleted"],
    TotalRecords = (int)dataRow["TotalRecords"]
};

并将对象添加到列表

DataList.Add(demoValue);

我的清单是

public List<DemoData> DataList = new List<DemoData>();

我的班级是

public class DemoData
{
    public string CompanyName { get; set; }
    public DateTime DateCompleted { get; set; }
    public int TotalRecords { get; set; }
}

4 个答案:

答案 0 :(得分:0)

如果DemoData 已完成,答案取决于您要执行的业务逻辑:

您可能希望坚持null;然而,它使逻辑更多复杂(因为null现在是特殊情况),并且需要DemoData修改:

public class DemoData
{
     public string CompanyName { get; set; }
     // DateTime? - DateCompleted is Nullable<DateTime>   
     public DateTime? DateCompleted { get; set; }
     public int TotalRecords { get; set; }
}
...

DemoData demoValue = new DemoData {
  CompanyName = dataRow["CompanyName"].ToString(),
  DateCompleted = dataRow.IsDbNull("DateCompleted") 
    ? null // <- now we can assign null to Nullable<T>   
    : (DateTime?) dataRow["DateCompleted"],
  TotalRecords = (int)dataRow["TotalRecords"]
};

您可能希望采用以下(典型)逻辑:“如果DemoData已完成 ,则最终将 完成) future “:

...
if (dataRow["DateCompleted"] == DBNull.Value)
{
    // Well, at 31 Dec 9999 it'll be completed for sure...
    dataRow["DateCompleted"] = DateTime.MaxValue;
}

...

DemoData demoValue = new DemoData
{
  CompanyName = dataRow["CompanyName"].ToString(),
  DateCompleted = (DateTime)dataRow["DateCompleted"],
  TotalRecords = (int)dataRow["TotalRecords"]
};

答案 1 :(得分:0)

所以我发现问题是我正在为dataRow本身分配空值,所以它不接受任何值,我写了这样的代码,现在它工作正常

DateTime? dateCompleted;
if (dataRow["DateCompleted"] == DBNull.Value)
{
    dateCompleted= null;
}
else
{
    dateCompleted= (DateTime)dataRow["DateCompleted"];
}
DemoData demoValue = new DemoData
{
    CompanyName = dataRow["CompanyName"].ToString(),
    DateCompleted = dateCompleted,
    TotalRecords = (int)dataRow["TotalRecords"]
};

和班级

public class DemoData
{
     public string CompanyName { get; set; }
     public DateTime? DateCompleted { get; set; }
     public int TotalRecords { get; set; }
}

答案 2 :(得分:-1)

让你的班级DateCompleted可以为空:

public class DemoData
{
    public string CompanyName { get; set; }
    public DateTime? DateCompleted { get; set; }
    public int TotalRecords { get; set; }
}

答案 3 :(得分:-1)

由于你的源代码是一个像这样的数据表

            DataTable dt = new DataTable();
            dt.Columns.Add("date", typeof(DateTime));
            dt.Columns["date"].AllowDBNull = true;

            dt.Rows.Add();
            dt.Rows[0]["date"] = DBNull.Value;