Is it possible to insert an item into a NameValueCollection in a specific index? I don't see an Insert() method.
+1
A:
No, there is no method to insert an item at a specific index. However, it should be trivial to write a extension method for doing that.
What's the reason you're using a NameValueCollection?
alexn
2009-12-17 17:32:15
A:
This is not really what NameValueCollection
s are meant for; if you need to manipulate your collection in this way you should consider a different data structure (OrderedDictionary
?). That said, here's an extension method that will do what you want:
static class NameValueCollectionExtensions {
public static void Insert(this NameValueCollection collection, int index, string key, string value) {
int count = collection.Count;
if (index < 0 || index > count) {
throw new ArgumentOutOfRangeException("index");
}
List<string> keys = new List<string>(collection.AllKeys);
List<string> values = keys.Select(k => collection[k]).ToList();
keys.Insert(index, key);
values.Insert(index, value);
collection.Clear();
for (int i = 0; i <= count; i++) {
collection.Add(keys[i], values[i]);
}
}
}
I don't know that collection.AllKeys
is guaranteed to return the keys in the order that they were inserted. If you can find documentation stating that this is the case then the above is fine. Otherwise, replace the line
List<string> keys = new List<string>(collection.AllKeys);
with
List<string> keys = new List<string>();
for(int i = 0; i < count; i++) {
keys.Add(collection.Keys[i]);
}
Jason
2009-12-17 17:48:48
A:
Here's an implementation of an Insert
extension method for NameValueCollection
:
static class ColExtensions
{
private class KeyValuesPair
{
public string Name { get; set; }
public string[] Values { get; set; }
}
public static void Insert(this NameValueCollection col, int index, string name, string value)
{
if (index < 0 || index > col.Count)
throw new ArgumentOutOfRangeException();
if (col.GetKey(index) == value)
{
col.Add(name, value);
}
else
{
List<KeyValuesPair> items = new List<KeyValuesPair>();
int size = col.Count;
for (int i = index; i < size; i++)
{
string key = col.GetKey(index);
items.Add(new KeyValuesPair
{
Name = key,
Values = col.GetValues(index),
});
col.Remove(key);
}
col.Add(name, value);
foreach (var item in items)
{
foreach (var v in item.Values)
{
col.Add(item.Name, v);
}
}
}
}
}
bruno conde
2009-12-17 18:27:53