An elegant way to handle null references in chain methods of the XElement axis

Given something like this:

var results = theElement.Element("Blah").Element("Whatever").Elements("Something"); 

Is there an elegant way to deal with zero Blah or any element, so the results in this case are just empty or empty?

I know that I can split the query and manually perform these checks, but wondered if there was anything more concise.

+6
source share
1 answer

You can add some extension methods to do this for you. For the Element method, you must return null or the element itself. For the Elements method, you must return an empty result or target elements.

These are extension methods:

 public static class XElementExtensions { public static XElement ElementOrDefault(this XElement element, XName name) { if (element == null) return null; return element.Element(name); } public static IEnumerable<XElement> ElementsOrEmpty(this XElement element, XName name) { if (element == null) return Enumerable.Empty<XElement>(); return element.Elements(name); } } 

You can use them as follows:

 var query = theElement.ElementOrDefault("Blah") .ElementOrDefault("Whatever") .ElementsOrEmpty("Something"); if (query.Any()) // do something else // no elements 

If you are not requesting ElementsOrEmpty , but your last request is for ElementOrDefault , you should check for null instead of the Enumerable.Any method.

+6
source

Source: https://habr.com/ru/post/890927/


All Articles