Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use collection initializers with a NameValueCollection?

Tags:

c#

collections

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

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

Thanks

like image 851
gap Avatar asked Feb 24 '11 16:02

gap


People also ask

Is NameValueCollection case sensitive?

The default comparer is a CaseInsensitiveComparer that uses the conventions of the invariant culture; that is, key comparisons are case-insensitive by default. To perform case-sensitive key comparisons, call the NameValueCollection.

What is NameValueCollection in c#?

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold multiple string values under a single key.

What is collection initializers in C#?

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer.

What is an initializer list Visual Basic?

Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values.


2 Answers

Yes; just uses braces instead of parentheses.

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

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

like image 100
SLaks Avatar answered Oct 23 '22 14:10

SLaks


You can use collection initializers with everything that has Add method. Yeah, duck typing. If Add has more then 1 param put tuples in curly bracets:

NameValueCollection nvc = new NameValueCollection() { { "a", "1" }, { "b", "2" } }; 
like image 26
Andrey Avatar answered Oct 23 '22 14:10

Andrey