C# Iterate through NameValueCollection

C#CollectionsNamevaluecollection

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

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

Solution 3 - C#

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);

Solution 4 - C#

var enu = myNameValueCollection.GetEnumerator();
while (enu.MoveNext())
{
    string key = (string)enu.Current;
    string value = myNameValueCollection[key];
}

OR when keys nullable:

for (int i = 0; i < myNameValueCollection.Count; i++)
{
    string key = myNameValueCollection.GetKey(i);
    string value = myNameValueCollection.Get(i);
}

Solution 5 - C#

The only way I found to avoid the nested loops is using additional List to store the values:

List<string> arrValues = new List<string>();
for (int i = 0; i < nvc.Count; i++)
	arrValues.AddRange(nvc.GetValues(i));
foreach (string value in arrValues)
	Console.WriteLine(value);

(Requires [only] .NET 2.0 or later)

Solution 6 - C#

I think this is simpler: VB.NET

For i As Integer = 0 To nvc.Count - 1
   Console.Write("No", "Key", "Value")
   Console.Write(i, nvc.GetKey(i), nvc.Get(i))
Next

C#:

for (int i = 0; i <= nvc.Count - 1; i++)
{
    Console.Write("No", "Key", "Value");
    Console.Write(i, nvc.GetKey(i), nvc.Get(i));
}

Solution 7 - C#

for (int i = 0; i < nvc.Count; i++) {
	System.Console.WriteLine(

		nvc.AllKeys[i] + " = " + nvc[i]

	);
}

Solution 8 - C#

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

This will return you all keys and corresponding values.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul MichaelsView Question on Stackoverflow
Solution 1 - C#JulianView Answer on Stackoverflow
Solution 2 - C#Fredrik MörkView Answer on Stackoverflow
Solution 3 - C#Ruben BartelinkView Answer on Stackoverflow
Solution 4 - C#Dmitry ShashurovView Answer on Stackoverflow
Solution 5 - C#Shadow Wizard Says No More WarView Answer on Stackoverflow
Solution 6 - C#Hannington MamboView Answer on Stackoverflow
Solution 7 - C#Kirby L. WallaceView Answer on Stackoverflow
Solution 8 - C#Sachin ShanbhagView Answer on Stackoverflow