[英]How to convert a nullable datetime value to string.empty when datetime is null?
I'm reading back a nullable DateTime?
我正在读回一个可以为空的
DateTime?
property then assigning that value to a string property in short date format. 属性然后以短日期格式将该值分配给字符串属性。
I can convert the date time value to a short date string and assign to the IT_Date_String
property. 我可以将日期时间值转换为短日期字符串并分配给
IT_Date_String
属性。 But I'm not sure how to assign a ""
value to the string if the IT_Date
is null. 但是,如果
IT_Date
为null,我不确定如何为字符串赋值""
。
How can you convert a datetime? 你如何转换日期时间? value to string.empty when datetime?
datetime时为string.empty的值? is null?
一片空白?
This is the assignment in linq: 这是linq中的赋值:
var status_list = query_all.ToList().Select(r => new RelStatus
{
IT_Date_String = r.IT_Date.Value.ToString("yyyy-MM-dd") != null ? r.IT_Date.Value : null
}).ToList();
And the properties in the model: 以及模型中的属性:
public DateTime? IT_Date { get; set; }
public string IT_Date_String { get; set; }
You're calling the IT_Date.Value.ToString(...)
regardless of whether IT_Date
actually has a value. 无论
IT_Date
是否实际具有值,您都在调用IT_Date.Value.ToString(...)
。
So you need to turn the expression around: 所以你需要转动表达式:
r.IT_Date.HasValue ? r.IT_Date.Value.ToString(...) : ""
This way ToString()
will only be called when IT_Date
has a value. 这样,只有在
IT_Date
有值时IT_Date
调用ToString()
。
You can also implement this in the getter, as mentioned in a now-deleted comment: 您也可以在getter中实现它,如现在删除的注释中所述:
public string IT_Date_String
{
get
{
return IT_Date.HasValue ? IT_Date.Value.ToString(...) : "";
}
}
This way you won't have to reimplement the logic everywhere you access this model, and as a bonus, it will only be executed when it's actually requested. 这样您就不必在访问此模型的任何地方重新实现逻辑,作为奖励,它只会在实际请求时执行。
There's also no need to explicitly use String.Empty
, the string ""
will be interned to the same at runtime . 也没有必要显式使用
String.Empty
,字符串""
将在运行时被实例化 。
In C# 6 you can do this: 在C#6中,您可以这样做:
IT_Date_String = r.IT_Date?.ToString("yyyy-MM-dd") ?? String.Empty;
The new ?
新的
?
checks if the thing on the left is null, if it is, the expression evaluates to null
. 检查左边的东西是否为null,如果是,则表达式求值为
null
。 If not, it just continues the evaluation. 如果没有,它只是继续评估。
Then, ??
然后,
??
checks whether the result of the first expression is null
, which it would be if IT_Date
is null. 检查第一个表达式的结果是否为
null
,如果IT_Date
为null,则为空。 If it is, evaluate to String.Empty
. 如果是,则计算为
String.Empty
。
使用C#6.0和null传播,您可以使用:
IT_Date_String = r.IT_Date?.ToString("yyyy-MM-dd") ?? String.Empty
这个适用于任何版本的框架:
IT_Date_String=string.Format("{0:yyyy-MM-dd}",IT_Date);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.