我正在尝试解析那里有日期的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),
});
我正在使用的对象是......
class PatientClass
{
public DateTime? PCPAppointmentDateTime { get; set; }
}
有什么想法吗?
答案 0 :(得分:5)
您应该在方法中包装Parse
。返回DateTime
。
DateTime ValueOrMin(string value)
{
if (string.IsNullOrWhiteSpace(value)) return DateTime.MinValue;
return DateTime.Parse(value);
}
答案 1 :(得分:2)
除了显而易见的方法之外,没有“简单”的方法,这也不是那么复杂:
var dateString = templates.Descendants("element")
.SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime")
.Attribute("value").Value;
PCPAppointmentDateTime = dateString == ""
? DateTime.MinValue
: DateTime.Parse(dateString);
答案 2 :(得分:2)
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;
}