2016-10-14 23 views
1

我試圖將字符串轉換爲DateTime?使用DateTime.Parse()但只有當字符串不爲空時。我試圖使用空,條件運算符正確使用空條件運算符與DateTime.Parse()

這就是我試圖取代:

string maxPermissableEndDate = response.Contract.ReferenceFields.FirstOrDefault(t => t.code == "MAX_EXT_DATE")?.Value; 

if (!string.IsNullOrEmpty(maxPermissableEndDate)) 
{ 
    contract.MaximumPermissableEndDate = DateTime.Parse(maxPermissableEndDate); 
} 

我如何分配給可空的DateTime屬性MaximumPermissableEndDate只有這種有吸引力的方式當變量maxPermissableEndDate不爲空?

這是我期待在從C#6.0文檔中的例子:

string result = value; 

if (value != null) // Skip empty string check for elucidation 
{ 
    result = value.Substring(0, Math.Min(value.Length, length)); 
} 

了替代的幸福:

value?.Substring(0, Math.Min(value.Length, length)); 

回答

0

你可以做到這一點是這樣的:

contract.MaximumPermissableEndDate = string.IsNullOrEmpty(maxPermissableEndDate) ? 
    contract.MaximumPermissableEndDate 
    : new Nullable<DateTime>(DateTime.Parse(maxPermissableEndDate)); 
2

這不使用空COALESCE運營商的事,但喜歡這個?

DateTime attemptParseDate; 
contract.MaximumPermissableEndDate = 
DateTime.TryParse(maxPermissableEndDate, out attemptParseDate)? 
    attemptParseDate : (DateTime?) null;