SoftwareSavant
SoftwareSavant

Reputation: 9757

DateTime.Min Value when string equals EmptyOr Null in Linq to XML

I am attempting to parse an xml string that has dates in there. The object that I am trying to fill has a nullable DateTime. But if the string that I pull back has an empty value, I want it to be the min Date Value. and I want to assign that to the variable? Is there a simple way to do that using 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),
 });

The object that I am using is this...

 class PatientClass
 { 
   public DateTime? PCPAppointmentDateTime { get; set; }
 }

Any ideas?

Upvotes: 1

Views: 1649

Answers (3)

Fourth
Fourth

Reputation: 9351

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;
}

Upvotes: 2

Roman Starkov
Roman Starkov

Reputation: 61502

There’s no "simple" way other than the obvious approach, which isn’t that complicated either:

var dateString = templates.Descendants("element")
      .SingleOrDefault(el => el.Attribute("name").Value == "PCPAppointmentDateTime")
      .Attribute("value").Value;
PCPAppointmentDateTime = dateString == ""
      ? DateTime.MinValue
      : DateTime.Parse(dateString);

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190976

You should wrap Parse in a method. Return a DateTime.

DateTime ValueOrMin(string value)
{
     if (string.IsNullOrWhiteSpace(value)) return DateTime.MinValue;
     return DateTime.Parse(value);
}

Upvotes: 5

Related Questions