Vivekh
Vivekh

Reputation: 4259

linq condition to accept null dictionary(Value) if not passed by treating it as null

I have this validation where it checks whether key and value are valid or not in the Dictionary but have to modify it to accept null Key Dictionary and treat it as an Empty collection while checking for inner key and value

change the logic to accept value as null for the Dictionary

List<KeyValuePair<string, Dictionary<string, string>>> properties = new List<KeyValuePair<string, Dictionary<string, string>>>();
properties.Add(new KeyValuePair<string, Dictionary<string, string>>("test", null));
var list = properties.Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(value => string.IsNullOrWhiteSpace(value))));

It is being failed when i pass null. please let me know what i need to change in select statement to treat null as an Empty inner Dictionary

Upvotes: 0

Views: 1683

Answers (2)

ASh
ASh

Reputation: 35720

since you want to treat null value Dictionary as empty and empty dictionary doesn't have keys or values, you should probably ignore null values:

var list = properties.Where(p => p.Value != null)
           .Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) 
                       || cat.Value.Values.Any(value => string.IsNullOrWhiteSpace(value))));

Upvotes: 2

ApInvent
ApInvent

Reputation: 251

You need check cat.Value for null before access to it property:

    var properties = new List<KeyValuePair<string, Dictionary<string, string>>>
    {
        new KeyValuePair<string, Dictionary<string, string>>("test", null)
    };
    var list = properties.Select(cat => cat.Value != null && (cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(string.IsNullOrWhiteSpace))));

Or you can do this:

    var list = properties
        .Select(kvp=> new KeyValuePair<string, Dictionary<string,string>>(kvp.Key, kvp.Value ?? new Dictionary<string, string>()))
        .Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(string.IsNullOrWhiteSpace)));

Upvotes: 1

Related Questions