从解析字符串值的单行条件语句将 null 传递到 DataTable
我有一个应用程序,它循环遍历固定宽度的文本文件,将每一行读入字符串变量,并使用 .Substring() 方法查找给定字段的数据。对于给定字段,它检查内容是否只是空格,或者其中是否实际上有“数据”,即除空格之外的任何内容。例如,如果有数据,并且该数据表示日期,则对该数据运行 DateTime.Parse() 并将其传递到 C# DataTable 中的 datetime 类型的字段;但是,如果没有数据——只有空格,我只想将空值传递给该字段。下面是一段代码来说明:
var dataTable = new DataTable();
dataTable.Columns.Add("Application_Date").DataType = Type.GetType("System.DateTime");
while (!sr.EndOfStream)
{
string row = sr.ReadLine();
if (row.Substring(0, 1) == "2" && row.Substring(42, 1) == "T")
{
DataRow dr = dataTable.NewRow();
dr["Application_Date"] = row.Substring(124, 8) != " " ?
DateTime.Parse(row.Substring(124, 4) +
"-" + row.Substring(128, 2) + "-" +
row.Substring(130, 2)) :
null as DateTime?;
}
}
我的问题是,当我尝试运行它时,它会抛出一个错误,指出它需要 DBNull(无法将列“Application_Date”设置为空。请改用 DBNull。
当我尝试简单地传递 DBNull 时,它告诉我它无法在 DateTime 和 DBNull 之间转换(条件表达式的类型无法确定,因为 'System.DateTime? 之间没有隐式转换? ' 和 'System.DBNull'
)
我在这里缺少什么?
I have an app that loops through a fixed width text file, reads each line into a string variable and uses the .Substring() method to find data for a given field. For a given field, it checks to see if the contents are simply spaces, or if there is actually "data" in it, i.e. anything but spaces. If there is data, and that data represents a date, for instance, then DateTime.Parse() is run on that data and passed to a field of type datetime in a C# DataTable; however, if there is no data--just spaces, I want to simply pass a null value to the field. Here is a snippet of code to illustrate:
var dataTable = new DataTable();
dataTable.Columns.Add("Application_Date").DataType = Type.GetType("System.DateTime");
while (!sr.EndOfStream)
{
string row = sr.ReadLine();
if (row.Substring(0, 1) == "2" && row.Substring(42, 1) == "T")
{
DataRow dr = dataTable.NewRow();
dr["Application_Date"] = row.Substring(124, 8) != " " ?
DateTime.Parse(row.Substring(124, 4) +
"-" + row.Substring(128, 2) + "-" +
row.Substring(130, 2)) :
null as DateTime?;
}
}
My problem is that when I try to run this, it throws an error saying it wants a DBNull (Cannot set Column 'Application_Date' to be null. Please use DBNull instead.
)
But when I attempt to simply pass a DBNull instead, it tells me that it can't convert between DateTime and DBNull (Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime?' and 'System.DBNull'
)
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
DateTime
转换为object
才能在条件中使用它:You need to cast the
DateTime
toobject
to use it in the conditional:使用空合并运算符:
Using the null-coalescing operator: