Using DefaultIfEmpty() to check if an element exists with LINQ

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.

Comments (1) -

  • IMHO DefaultIfEmpty is not the most straightforward way to do this.
    Maybe you should use Count() > 0 or Any()

    if (xmlFromFile.Elements.("anElement").Descendants("someElement").Any())
    // do your job if at least one element is present

    if you want to work with elements and make any actions if there are no elements in sequence without restarting IEnumerable<T> "feed" you could try something like just "bool processedAtLeastOneElement = false" and in the body of your foreach write "processedAtLeastOneElement = true" and after foreach "if (!processedAtLeastOneElement)". Advantages: no dummy creation, no magic "if" with magic string content "Does Not Exist" (what if typo Smile ). Sorry for writing long comments...
Comments are closed