Home > Software engineering >  Handling Dictionary values incase if it is null
Handling Dictionary values incase if it is null

Time:06-22

I have two dictionaries

Dictionary<string, string> dictionary1 = new Dictionary<string, string>();
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();

The requirement is to get all the values from dictionary1 and uncommon from dictionary2, which anyways I have implemented.

The only issue is if anyone of the dictionaries is null I am getting an exception, I want to handle this null scenario. If any of the dictionaries is null then return the other dictionary.

var demo = dictionary1 .Concat(dictionary2 .Where(kvp => !dictionary1 .ContainsKey(kvp.Key))).ToList();

Can someone please guide me on how to do that?

CodePudding user response:

You can check if dictionary is null (and create empty one) before query:

dictionary1 ??= new Dictionary<string, string>();
dictionary2 ??= new Dictionary<string, string>();

// no changes
var demo = dictionary1.Concat(dictionary2.Where(kvp => !dictionary1.ContainsKey(kvp.Key))).ToList();

CodePudding user response:

Using null instead of empty collection is often a bad practice, however if you have to work with null dictionaries you can use ?. instead of just .

// let's return empty list (not null) if any of dictionary is null
// if you want to have demo being null, remove ?? ... fragment
var demo = dictionary1
  ?.Concat(dictionary2
              ?.Where(kvp => dictionary1
              ?.ContainsKey(kvp.Key) == false))
  ?.ToList() ?? new List<KeyValuePair<string, string>>();

the only small difficulty is with ?.ContainsKey(...): it returns bool? instead of bool that's why we can't put ! but have to compare with false or true.

CodePudding user response:

Using Concat is a not a good idea, since the main advantage of a dictionary, i.e., a constant lookup time, gets lost!

Use the null-coalescing operator instead:

if ((dictionary1 ?? dictionary2).TryGetValue(key, out string value)) {
    ...
}

If both dictionaries can be null, you can add a third term:

dictionary1 ?? dictionary2 ?? new Dictionary<string, string>()

or create an empty dictionary that you can reuse in this situation:

static readonly Dictionary<string, string> emptyDict = new();

...

if ((dictionary1 ?? dictionary2 ?? emptyDict).TryGetValue(key, out string value)) {
    ...
}

Null-coalescing operator chains a ?? b ?? c ?? d return the first non-null value if any and otherwise null.

  • Related