简体   繁体   中英

c# - check for null in a collection initializer

I am parsing a Json document using Json.NET and creating an ArrayList using a Collection Initializer as follows

var array = new ArrayList
            {
                  inputJson["abc"].ToString(),
                  inputJson["def"].Value<float>(),
                  inputJson["ghi"].Value<float>()
            };

Now I would like to add a null check so it doesn't throw an exception if one of the properties is missing in the Json document.

Thanks

Something like this would do the trick

var array = new ArrayList
{
      inputJson["abc"] != null ? inputJson["abc"].ToString() : "",
      inputJson["def"] != null ? inputJson["def"].Value<float>() : 0.0F,
      inputJson["ghi"] != null ? inputJson["ghi"].Value<float>() : 0.0F
};

I would create extension methods to handle this. Note, I'm not positive on the types here, so bear with me:

public static string AsString(this JObjectValue jsonValue, string defaultValue = "")
{
    if (jsonValue != null)
        return jsonValue.ToString();
    else
        return defaultValue;
}

public static T As<T>(this JObjectValue jsonValue, T defaultValue = default(T))
{
    if (jsonValue != null)
        return jsonValue.Value<T>();
    else
        return defaultValue;
}

With usage:

var array = new ArrayList
{
    inputJson["abc"].AsString(),
    inputJson["def"].As<float>(),
    inputJson["ghi"].As<float>(),
    inputJson["jkl"].As(2.0f) //or with custom default values and type inference
};

This also has the benefit of avoiding hitting the indexer twice (once to check for null , and a second time to convert the value), and avoids repeating yourself as to how you parse/read the json input.

You can try this :

var array = new ArrayList
{
      inputJson["abc"] ?? inputJson["abc"].ToString(),
      ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM