Nick
Nick

Reputation: 3965

Casting a LINQ date to a DateTime in C#?

I'm trying to get a list of all of the UIDs from this XML where the date is more than 6 months ago:

<Photos>
  <Photo UID="b68552e32a4f47f592fb737adf305a4d">
    <Date>2014-01-22T10:20:09.078873+01:00</Date>
    <File>b68552e32a4f47f592fb737adf305a4d.JPG</File>
  </Photo>
  <Photo UID="2802f727a8c74e15ae8fe20dbd0d7137">
    <Date>2013-08-22T10:20:10.278873+01:00</Date>
    <File>2802f727a8c74e15ae8fe20dbd0d7137.JPG</File>
  </Photo>
  <Photo UID="dd51105cf6ca4bd88a6a2f521d935ea7">
    <Date>2014-08-22T10:20:33.998873+01:00</Date>
    <File>dd51105cf6ca4bd88a6a2f521d935ea7.JPG</File>
  </Photo>
</Photos>

I'm using the following LINQ code:

var fileList = xml.Descendants("Photo")
       .Where(e => e.Attribute("Date") < DateTime.Now.AddMonths(-6))
       .Select("UID")
       .ToList();

However, it says it cannot compare the two variables in the where clause, so I tried using a cast with no joy, and eventually trying a DateTime.Parse:

.Where(e => DateTime.Parse(e.Attribute("Date")) < DateTime.Now.AddMonths(-6))

But I get an error saying that DateTime.Parse() has some invalid arguments.

Any idea what I'm doing wrong please?

Many thanks

Upvotes: 0

Views: 393

Answers (4)

JLRishe
JLRishe

Reputation: 101652

This should do it:

.Where(e => DateTime.Parse((string)e.Element("Date")) < DateTime.Now.AddMonths(-6))
.Select(e => Guid.Parse((string)e.Attribute("UID")))
.ToList()

Note that Date is an element, not an attribute.

Upvotes: 0

Neel
Neel

Reputation: 11721

Try below code using XmlConvert.ToDateTime Method :-

IEnumerable<Guid> uids = xml.Descendants("Photo")
   .Where(e => XmlConvert.ToDateTime(e.Element("Date").Value, XmlDateTimeSerializationMode.Utc) < DateTime.Now.AddMonths(-6))
       .Select(e => Guid.Parse(e.Attribute("UID").Value))
       .ToList();

Upvotes: 2

Mike Miller
Mike Miller

Reputation: 16575

Date isn't an attribute but a node, you want /Photo/Date not /Photo[@Date]

Also use XMLConvert.ToDate and that will safely unpack the value back to a datetime.

xml.Descendants("Photo").Where(e => XmlConvert.ToDateTime(e.Element("Date").Value, XmlDateTimeSerializationMode.Utc) < DateTime.Now.AddMonths(-6)).ToList();

Upvotes: 1

Eldar Dordzhiev
Eldar Dordzhiev

Reputation: 5135

Attribute method returns XAttribute, not string. In order to obtain it's value, you need to use Value property.

var fileList = xml.Descendants("Photo")
       .Where(e => DateTime.Parse(e.Attribute("Date").Value) < DateTime.Now.AddMonths(-6))
       .Select("UID")
       .ToList();

Upvotes: 1

Related Questions