DateTime.Min当字符串等于Linq中的EmptyOr Null为XML时的值

Sof*_*ant 1 c# linq-to-xml

我试图解析一个在那里有日期的xml字符串.我想要填充的对象具有可为空的DateTime.但是如果我拉回的字符串有一个空值,我希望它是最小日期值.我想将它分配给变量?使用LINQ有一种简单的方法吗?

 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),
 });
Run Code Online (Sandbox Code Playgroud)

我正在使用的对象是......

 class PatientClass
 { 
   public DateTime? PCPAppointmentDateTime { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Dan*_*ite 5

你应该包装Parse一个方法.回来一个DateTime.

DateTime ValueOrMin(string value)
{
     if (string.IsNullOrWhiteSpace(value)) return DateTime.MinValue;
     return DateTime.Parse(value);
}
Run Code Online (Sandbox Code Playgroud)