Sep 9, 2008

Linq To XML : Check for existence of an 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};


The trick is to use the Elements(“node”) instead of Element(“node”) and then use the Any() function which will return true if an element of that name exists.

Some other LINQ tips:

Some of the extensions that one can use are Intersect,Union && Except
var list1 = new List<int> { 2, 4, 9, 11, 3, 6 };
var list2 = new List<int> { 3, 8, 4, 30, 9, 16 };
var newlist = list1.Intersect(list2);

This returns : 3,4,9
newlist = list1.Union(list2);
this returns : 2,3,4,6,8,9,11,16,30. finally
newlist = list1.Except(list2);
returns : 2,11,6

kick it on DotNetKicks.com

No comments: