Can I use collection initializers with NameValueCollection?

Is there a way to initialize NVC using the C # collection initializer syntax:

NameValueCollection nvc = new NameValueCollection() { ("a", "1"), ("b", "2") }; 

thank

+71
collections c #
Feb 24 '11 at 16:23
source share
2 answers

Yes; just uses parentheses instead of parentheses.

 var nvc = new NameValueCollection { {"a", "1"}, {"b", "2"} }; 

You can call Add methods with arbitrary sets of parameters using syntax.

+111
Feb 24 '11 at 16:24
source share
— -

You can use collection initializers with everything that the Add method has. Yes, the duck is printing. If Add has more than 1 pair, put the tuples in braces:

 NameValueCollection nvc = new NameValueCollection() { { "a", "1" }, { "b", "2" } }; 
+7
Feb 24 '11 at 16:25
source share



All Articles