C# Iterate through NameValueCollection

You can flatten the collection with Linq, but it's still a foreach loop but now more implicit.

var items = nvc.AllKeys.SelectMany(nvc.GetValues, (k, v) => new {key = k, value = v});
foreach (var item in items)
    Console.WriteLine("{0} {1}", item.key, item.value);

The first line, converts the nested collection to a (non-nested) collection of anonymous objects with the properties key and value.

It's flatten in the way that it's now a mapping key -> value instead of key -> collection of values. The example data:

Before:

Test -> [Val],

Test2 -> [Val1, Val1, Val2],

Test3 -> [Val1],

Test4 -> [Val4]

After:

Test -> Val,

Test2 -> Val1,

Test2 -> Val1,

Test2 -> Val2,

Test3 -> Val1,

Test4 -> Val4


You can use the key for lookup instead of having two loops:

foreach (string key in nvc)
{
    Console.WriteLine("{0} {1}", key, nvc[key]);
}

Nothing new to see here (@Julian's +1'd by me answer is functionally equivalent), y'all move along y'all please.


I have an [overkill for this case but possibly relevant] set of extension methods in an answer to a related question, which would let you do:

foreach ( KeyValuePair<string,string> item in nvc.AsEnumerable().AsKeyValuePairs() )
    Console.WriteLine("{0} {1}", item.key, item.value);