I have a NameValueCollection
, 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);
Console.ReadLine();
Is there?
The only way I found to avoid the nested loops is using additional List to store the values:
(Requires [only] .NET 2.0 or later)
You can use the key for lookup instead of having two loops:
I think this is simpler:
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:
You can flatten the collection with Linq, but it's still a
foreach
loop but now more implicit.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:
After:
This will return you all keys and corresponding values.