C# Linq to XML check if element exists

Goober picture Goober · Jun 24, 2009 · Viewed 29.9k times · Source

I have an XML document as follows:

<Database>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
 </SMS>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
 </SMS>
</Database>

I am trying to check whether the number child node of the parent SMS node exists in the document (for validation purposes to avoid inserting duplicate data).

Any advice on a potential solution?

EDIT: The element will be compared to an input string. For example if(inputNumber == xmlDocNumber){ //Don't Insert New Element }

Answer

Jon Skeet picture Jon Skeet · Jun 24, 2009

I'll suggest a slightly different tack to using Count() - use Any(). The advantage is that Any() can stop as soon as it gets any matches at all:

var smsWithNoNumber = main.Descendants("SMS")
                          .Where(x => !x.Elements("Number").Any());

In this case it won't make much odds, but in cases where Count() might have to count a million hits just to tell you that there was at least one, it's a useful trick to know. I'd say it's also a clearer indicator of what you mean.