This is a very handy way to test if an element exists using LINQ
Often you want to run something only if an element exists.
There is always the try/catch method, but that doesn't seem very elegant to me, and this gave me an excuse to figure some more out about LINQ, which I am finding I like more and more.
This is actually very simple once you understand how DefaultIfEmpty() works.
It may seem a bit obvious, but it returns a default value if something is not there.
The easiest way to do this is to give it something explicitly so you know what it is returning for the default; I just use a dummy instance.
For this example, I am using LINQ with XML and XElements
//make your dummy element
XElement dummy = new XElement("dummy");
//assign it an easy to recognize null value
dummy.Value = "Does Not Exist";
//now run a query with it
foreach (XElement p in xmlFromFile.Elements("anElement").Descendants("someElement").DefaultIfEmpty(dummy))
{
if(process.Value.Equals("Does Not Exist")
//it does not exist
}
It's just that easy. Works the exact same with SQL or any other data source as well.