Search code examples
c#.netfor-loopforeachnamevaluecollection

Why "foreach" loop returns Key while "indexer" returns Value from a NameValueCollection


I have a NameValueCollection which contain several items. When I try to retrieve a value from that collection, it returns me the Key from the collection

NameValueCollection col= new NameValueCollection();
    col.Add("Item1", "Foo");
    col.Add("Item2", "Bar");
    col.Add("Item3", "Pooh");
    col.Add("Item4", "Car");
    foreach (string val in col) 
    {
       if (val == "Item3") //val contains the Key from the collection
          { break; }
    }

While on the other hand, if I try to retrieve the value from indexer in a for loop, then it returns me the Value from the collection

for (int i = 0; i < col.Count; i++) 
{
    string val = col[i];
    if (val == "Pooh") //val contains the 'Value' from the NameValueCollection
    {
       break;
    }
}

Why there are different type of results for these different type of loops?


Solution

  • NameValueCollection

    Represents a collection of associated String keys and String values that can be accessed either with the key or with the index.

    ForEach accesses the String key
    col[val] would access the value via the key

    In the second you are accessing the value via the index