1

I want to check if JArray.Children() is null in the foreach loop. I can do:

        if (jArrayJson == null)
        {
            return;
        }

but I want to do it in the foreach. This is the different things I have tried:

    JArray jArrayJson = (JArray)token.SelectToken("text");
    foreach (JToken item in jArrayJson?.Children() ?? Enumerable.Empty<T>()) // Wouldn't compile
    foreach (JToken item in jArrayJson?.Children()) // This will fail and not stop a null value

I saw this post about exention method, but I could not integrate the metod: Check for null in foreach loop

    public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
    {
        return source ?? Array.Empty<T>();
    }



foreach (JToken item in jArrayJson?.Children().OrEmptyIfNull()) // Wouldn't compile
        

1 Answers1

2

Apparently, Children() returns a custom JEnumerable type that is actually a struct, so cannot be null, which makes the null propagation awkward. So you could make this work using your first attempt, with a JToken in the type parameter (like Johnathan Barclay already suggested):

foreach (JToken item in jArrayJson?.Children() ?? Enumerable.Empty<JToken>())
{

}

Or I tweaked your extension method to work off a JToken itself:

public static JEnumerable<JToken> ChildrenOrEmptyIfNull(this JToken token)
{
    if(token == null)
    {
        return new JEnumerable<JToken>();
    }

    return token.Children();
}

which you could use like:

 foreach (JToken item in jArrayJson?.ChildrenOrEmptyIfNull())
 {

 }
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112