Search code examples
c#namevaluecollection

NameValueCollection key without value


I have a NameValueCollection variable queryDict.

Some of the keys have no values. However I would like to go through all keys, even if they have no values associated to them.

Using this, I get null instead of the key name if value is empty:

foreach (var parameter in queryDict)
{
  key = (string)parameter;
}

AllKeys produce all the results.

However I also get null. Looking at the content of queryDict, I can see with the string the value is there...

So how can I access all the key name without needing to create an algorithm?

Addition:

Here is the content of queryDict when hovering with the mouse:

{AQB=1&ndh=1&cid.&oxygenid}

cid. and oxygenid aren't found in the loop

I filled it this way:

string queryString = "AQB=1&ndh=1&cid.&oxygenid";
NameValueCollection queryDict = System.Web.HttpUtility.ParseQueryString(queryString);

Solution

  • A NameValueCollection allows you to add more than one value with the same key, but if you add a key with a null value and then readd again the same key with a not null value, the first value (the null one) is no more available

    Let's test some scenarios:

    NameValueCollection coll = new NameValueCollection();
    coll.Add("This", "Test");
    coll.Add("That", "A value");
    coll.Add("This", "Not a null");
    
    foreach (string p in coll.AllKeys)
    {
        Console.WriteLine("Key=" + p + ", Value=[" + (coll[p] ?? "null") + "]");
    }
    

    we get, as output,

    Key=This, Value=[Test,Not a null]
    Key=That, Value=[A value]
    

    So the object has merged the values of the two adds in a single entry separating the two values with a comma. Now let's try with

    coll.Add("This", null);
    coll.Add("That", "A value");
    coll.Add("This", "Not a null");
    

    The output is

    Key=This, Value=[Not a null]
    Key=That, Value=[A value]
    

    There is no trace of the first add. Why this happens? Simply because the internal logic of the Add method that merges the values cannot distinguish between the initial value of null and the null added by the first add. So it just replace the null value with the "Not a null" string.

    Indeed commenting the last add

    coll.Add("This", null);
    coll.Add("That", "A value");
    // coll.Add("This", "Not a null");
    

    we get

    Key=This, Value=[null]
    Key=That, Value=[A value]