Is there a way to initialize a NVC using C# collection initializer syntax:
NameValueCollection nvc = new NameValueCollection() { ("a", "1"), ("b", "2") };
Thanks
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.
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.
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.
Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values.
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.
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" } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With