Linq To XML : Check for existence of element

var bookQuery = 

from book in bookXml.Descendants("Item")
let attributes = book.Element("ItemAttributes")

let price = Decimal.Parse((
  book.Elements("OfferSummary").Any() 
  && book.Element("OfferSummary").Elements("LowestNewPrice").Any()
  ? book.Element("OfferSummary")
    .Element("LowestNewPrice")
    .Element("Amount").Value
  : (attributes.Elements("ListPrice").Any()
      ? attributes.Element("ListPrice").Element("Amount").Value 
      : "0"))) / 100

select new {Price = price};

Elements(“node”).Any() does the trick.

Some other Linq tips: Some extensions to use with Linq include: Intersect, Union and Except. Intersect returns a IEnumerable collection which is a inner join between the 2 collections. Union returns a collection which is a full outer join between the 2 collections Except returns elements unique to collection1 that don’t exist in the collection2.

Print | posted @ Monday, October 13, 2008 4:33 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
Twitter