Reputation: 2947
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);
Upvotes: 4
Views: 3057
Reputation: 216313
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]
Upvotes: 3
Reputation: 59
Try this and see if it works. You can loop through keys using NameValueCollection.AllKeys
without any duplicate returned.
foreach (var parameter in queryDict.AllKeys) { key = parameter; }
Upvotes: 0
Reputation: 61
Use ?? null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
Upvotes: 0
Reputation: 25370
I would like to go through all keys
You should loop through the keys then:
foreach (var parameter in queryDict.Keys)
Upvotes: 0