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
  • 32,440
  • 24
  • 112
  • 191
Revious
  • 7,383
  • 30
  • 94
  • 142

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,157
  • 16
  • 28
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
  • 32,606
  • 14
  • 101
  • 138
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
  • 148,824
  • 21
  • 237
  • 306
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,590
  • 2
  • 25
  • 35