pm_2 pm_2 - 2 months ago 19
C# Question

C# Iterate through NameValueCollection

I have a

, and want to iterate through the values. Currently, I’m doing this, but it seems like there should be a neater way to do it:

NameValueCollection nvc = new NameValueCollection();
nvc.Add("Test", "Val1");
nvc.Add("Test2", "Val1");
nvc.Add("Test2", "Val1");
nvc.Add("Test2", "Val2");
nvc.Add("Test3", "Val1");
nvc.Add("Test4", "Val4");

foreach (string s in nvc)
foreach (string v in nvc.GetValues(s))
Console.WriteLine("{0} {1}", s, v);


Is there?


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:


Test -> [Val],

Test2 -> [Val1, Val1, Val2],

Test3 -> [Val1],

Test4 -> [Val4]


Test -> Val,

Test2 -> Val1,

Test2 -> Val1,

Test2 -> Val2,

Test3 -> Val1,

Test4 -> Val4