我有这段代码:
command = new SqlCommand(query, connection);
reader = command.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(reader);
reader.Close();
connection.Close();
var data2 = dataTable.AsEnumerable().Select(x => new {
Datetime = x.Field<DateTime>("Datetime"),
Tagname = x.Field<String>("Tagname"),
Value = x.Field<Double>("Value")
});
当Value
字段为null
时,它会在投射过程中抛出异常。我怎么能防止这个例外?
答案 0 :(得分:8)
null
是double
使其可为空(如果Value
的类型可以为空或可以更改为
Value = x.Field<double?>("Value");
或定义在null
的情况下使用的默认值(例如,如果null
则为0)
Value = x.Field<double?>("Value") ?? 0;
答案 1 :(得分:0)
使用x.Field(&#34; Value&#34;)代替x.Field(&#34; Value&#34;)
var data2 = dataTable.AsEnumerable().Select(x => new {
Datetime = x.Field<DateTime>("Datetime"),
Tagname = x.Field<String>("Tagname"),
Value = x.Field <Double?>("Value")
});