loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 

C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

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

by naspinski 6/12/2008 5:12:00 AM

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

c# | linq

Related posts

Comments

7/22/2008 11:43:31 AM

Aibooster

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...

Aibooster ua

Add comment

Name*
E-mail* (Gravatar)
Website
Country   Country flag

Comment* [b][/b] - [i][/i] - [u][/u]- [quote][/quote]




Live preview

1/6/2009 3:06:34 AM