Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a single value from a NameValueCollection

My data source could have duplicate keys with values.

typeA : 1

typeB : 2

typeA : 11

I chose to use NameValueCollection as it enables entering duplicate keys.

I want to remove specific key\value pair from the collection, but NameValueCollection.Remove(key) removes all values associated with the specified key.

  1. Is there a way to remove single key\value pair from a NameValueCollection, OR
  2. Is there a better collection in C# that fits my data

[EDIT 1]

First, thanks for all the answers :)

I think I should have mentioned that my data source is XML.

I used System.Xml.Linq.XDocument to query for type and also it was handy to remove a particular value.

Now, my question is, for large size data, is using XDocument a good choice considering the performance? If not what are other alternatives (maybe back to NameValueCollection and using one of the techniques mentioned to remove data)

like image 969
Ayman Avatar asked Nov 03 '22 21:11

Ayman


2 Answers

The idea of storing multiple values with the same key is somehow strange. But I think you can retrieve all values using GetValues then remove the one you don't need and put them back using Set and then subsequent Add methods. You can make a separate extension method method for this.

like image 153
ElDog Avatar answered Nov 08 '22 03:11

ElDog


NameValueCollection doesn't really allow to have multiple entries with the same key. It merely concatenates the new values of existing keys into a comma separated list of values (see NameValueCollection.Add.

So there really is just a single value per key. You could conceivably get the value split them on ',' and remove the offending value.

Edit: @ElDog is correct, there is a GetValues method which does this for you so no need to split.

A better option I think would be to use Dictionary<string, IList<int>> or Dictionary<string, ISet<int>> to store the values as discrete erm, values

like image 23
Eli Algranti Avatar answered Nov 08 '22 03:11

Eli Algranti