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.
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 !=
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.
if(id == null) is the best method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With