How to load values ​​into a dictionary using {}

Can I load values ​​into a dictionary using {}?

This does not work

static Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { new KeyValuePair<byte, byte>(1, 1) }; 

This will not work, so I suspect there is syntax to load in {}

 static Dictionary<byte, byte> dic1252expand = new Dictionary<byte, byte>() { }; 

This is an example of syntax that works.

 byte[] bytes = new byte[] { 1, 2, 3 }; KeyValuePair<byte, byte> kvp = new KeyValuePair<byte, byte>(1, 1); 
+7
source share
5 answers

It works:

 Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { { 1, 1 }, { 2, 2 } }; 
+12
source

If you give someone fish, they have fish; if you teach them how to fish, you don’t need to give them fish. All posted answers are correct, but no one tells you how to determine the answer for yourself.

The syntax of a collection initializer in C # is "syntactic sugar"; it's just a nicer way to write boring code. When you write:

 C c = new C() { p, q, { r, s }, {t, u, v} }; 

This is the same as if you wrote:

 C c; C temporary = new C(); temporary.Add(p); temporary.Add(q); temporary.Add(r, s); temporary.Add(t, u, v); c = temporary; 

Now it should be clear how you can understand what to put in the initializer sentence: look at the type and see what the various Add methods take as arguments . In your case, the Add dictionary method takes a key and a value, so the initializer should be { { k1, v1 }, { k2, v2 } , ... }

Make sense?

+25
source
 Dictionary<string, string> d = new Dictionary<string, string>{{"s", "s"}}; 
+3
source
 var dict = new Dictionary<int, int>() { { 1, 1 }, { 2, 1 }, { 3, 2 } }; 

This will install a dictionary with three key value pairs.

+1
source
 Dictionary<byte, byte> d = new Dictionary<byte, byte>() { { 1, 2 }, { 3, 4 } }; 
+1
source

All Articles