C# Linq to XML中字符串等于EmptyOr Null时的DateTime.Min值
我试图解析一个包含日期的xml字符串。我尝试填充的对象具有可为空的DateTime。但是,如果我回调的字符串有一个空值,我希望它是mindate值。我想把它分配给变量?使用LINQ有没有一种简单的方法可以做到这一点C# Linq to XML中字符串等于EmptyOr Null时的DateTime.Min值,c#,linq-to-xml,C#,Linq To Xml,我试图解析一个包含日期的xml字符串。我尝试填充的对象具有可为空的DateTime。但是,如果我回调的字符串有一个空值,我希望它是mindate值。我想把它分配给变量?使用LINQ有没有一种简单的方法可以做到这一点 IEnumerable<PatientClass> template = (IEnumerable<PatientClass>)(from templates in xDocument.Descendants("dataTemplateSpecificati
IEnumerable<PatientClass> template = (IEnumerable<PatientClass>)(from templates in xDocument.Descendants("dataTemplateSpecification")//elem.XPathSelectElements(string.Format("//templates/template[./elements/element[@name=\"PopulationPatientID\"and @value='{0}' and @enc='{1}']]", "1", 0))
select new PatientClass
{
PCPAppointmentDateTime = DateTime.Parse(templates.Descendants("element").SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime").Attribute("value").Value),
});
有什么想法吗?您应该将Parse包装到一个方法中。返回日期时间
您应该在方法中包装解析。返回日期时间
除了显而易见的方法,没有简单的方法,也没有那么复杂:
var dateString = templates.Descendants("element")
.SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime")
.Attribute("value").Value;
PCPAppointmentDateTime = dateString == ""
? DateTime.MinValue
: DateTime.Parse(dateString);
除了显而易见的方法,没有简单的方法,也没有那么复杂:
var dateString = templates.Descendants("element")
.SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime")
.Attribute("value").Value;
PCPAppointmentDateTime = dateString == ""
? DateTime.MinValue
: DateTime.Parse(dateString);
为什么不使用null而不是神奇的值呢?出于兴趣,当有null可用时,为什么要使用DateTime.MinValue?如果您永远不会使用null值,为什么要麻烦让它可以为null呢?为什么不使用null而不是神奇的值呢?出于兴趣,当有null可用时,为什么要使用DateTime.MinValue?如果你永远不会使用空值,为什么还要麻烦让它可以为空呢?答案很好。我最终可能会这样做。我本以为这是一个很常见的问题,以至于Linq本身已经有了一些固有的功能。但是谢谢大家的帮助和建议。回答得好。我最终可能会这样做。我本以为这是一个很常见的问题,以至于Linq本身已经有了一些固有的功能。但是谢谢大家的帮助和建议。
var dateString = templates.Descendants("element")
.SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime")
.Attribute("value").Value;
PCPAppointmentDateTime = dateString == ""
? DateTime.MinValue
: DateTime.Parse(dateString);
public void DoWhatever(){
PCPAppointmentDateTime = ParseDate(templates.Descendants("element").SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime").Attribute("value").Value);
}
private DateTime ParseDate(string dateString){
DateTime date;
if (DateTime.TryParse(dateString, out date))
return date;
return DateTime.MinValue;
}