0

I would like to do something similar using some short syntax:

var p = new Dictionary<string, string>();
p["a"] = "2";
p["a"] = "3";

instead I have to do:

if (p.ContainsKey("a"))
    p["a"] = "2";
else
    p.Add("a", "2");

if (p.ContainsKey("a"))
    p["a"] = "3";
else
    p.Add("a", "3");

Does it exist a compact syntax?

Ian
  • 33,605
  • 26
  • 118
  • 198
Revious
  • 7,816
  • 31
  • 98
  • 147

4 Answers4

9

By the MSDN for Item property:

If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

So compact syntax exists

Rudis
  • 1,177
  • 15
  • 30
3
p["a"] = "2";

is equivalent to

if (!p.ContainsKey("a"))
    p.Add("a", "2");
else
    p["a"] = "2";

The first should be preffered in fact, because it is performed faster.

Athari
  • 33,702
  • 16
  • 105
  • 146
1

I have this extension method:

public static void AddOrKeep<K, V>(this IDictionary<K, V> dictionary, K key, V val)
{
    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, val);
    }
}

Use it like this:

dict.AddOrKeep("a", "2");

It keeps the current value if existent, but adds it if new.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

You can use ContainsKey Method of Dictionary to check whether particular Key contains by dictionary or not.

E.g.

if (!p.ContainsKey("a"))
{
p.Add("a","2");
}
else
{
p["a"] = "2";
}
Jignesh Thakker
  • 3,638
  • 2
  • 28
  • 35