Question

Curiously, is there a shorter way to write this in one line without having to reference the node twice? I find myself doing a lot of these in parsing.

lidID.idCountry = (passportnode.Descendants("COUNTRY").First().Value != String.Empty) ?
                      passportnode.Descendants("COUNTRY").First().Value :
                      "NONE"

or is the simplest way to make a temp variable for the value?

Was it helpful?

Solution

Although you need a temporary variable for that, you can hide it by defining an extension method:

public static ReplaceEmptyWith(this string original, string replacement) {
    return !string.IsNullOrEmpty(original) ? original : replacement;
}

Note that the temporary is still there - it's the first argument of the ReplaceEmptyWith method.

Now you can simplify your code as follows:

lidID.idCountry = passportnode
    .Descendants("COUNTRY")
    .First()
    .Value
    .ReplaceEmptyWith("NONE");

OTHER TIPS

The easiest way is to use a temp variable, like this:

var firstDescendantValue = passportnode.Descendants("COUNTRY").First().Value;
lidID.idCountry = firstDescendantValue != "" ? firstDescendantValue : "NONE";

However, if you really want a one liner, method time!

public SelfReturnIfTrue<T>(T source, Func<T, bool> predicate, T falseVal)
{
    return predicate(source) ? source : falseVal;
}

And then you can use it like this:

lidID.idCountry = SelfReturnIfTrue(passportnode.Descendants("COUNTRY").First().Value, string.IsNullOrEmpty, "NONE");

I think a temp variable would be a simple way to address this, or creating a function to handle it, like:

string GetValueIfValid(string s){
    return string.IsNullOrEmpty(s) ? "NONE" : s;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top