Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to deal with null references in chained XElement axis methods

Given something like this:

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

Is there an elegant way to deal with a null Blah or Whatever element so results is just null or empty in these cases?

I know I can split up the query and manually do these checks but was wondering if there was something more succinct.

like image 380
MangoBrainz Avatar asked Jun 20 '11 13:06

MangoBrainz


People also ask

How do you handle null values in LINQ query?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=

How do I avoid multiple nulls in Java 8?

We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional . That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the hood.

What is the best way to know if all the variables in a class are null?

if(id == null) is the best method.


1 Answers

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

These are the 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 in this manner:

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

If you're not querying for ElementsOrEmpty and your last request is for ElementOrDefault you would check for null instead of using the Enumerable.Any method.

like image 115
Ahmad Mageed Avatar answered Oct 23 '22 05:10

Ahmad Mageed