Using LINQ DefaultIfEmpty to Test If an Element Exists
Often you want to run something only if an element exists. There is always the Try/Catch method, but that introduces code overhead and increases resources if the Catch block is called. LINQ provides an extension called DefaultIfEmpty which returns a default value if the item does not exist in the list. 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 to XML and XElements.
LINQ DefaultIfEmpty Example:
//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(dummy.Value)
//it does not exist
}
Original artcle: http://naspinski.net/post/Using-DefaultIfEmpty-to-check-if-an-element-exists-with-LINQ.aspx
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
