How can I remove a item from list of KeyValuePair?
If you have both the key and the value you can do the following
public static void Remove<TKey,TValue>(
this List<KeyValuePair<TKey,TValue>> list,
TKey key,
TValue value) {
return list.Remove(new KeyValuePair<TKey,TValue>(key,value));
}
This works because KeyValuePair<TKey,TValue>
does not override Equality but is a struct. This means it uses the default value equality. This simply compares the values of the fields to test for equality. So you simply need to create a new KeyValuePair<TKey,TValue>
instance with the same fields.
EDIT
To respond to a commenter, what value does an extension method provide here?
Justification is best seen in code.
list.Remove(new KeyValuePair<int,string>(key,value));
list.Remove(key,value);
Also in the case where either the key or value type is an anonymous type, an extension method is required.
EDIT2
Here's a sample on how to get KeyValuePair where one of the 2 has an anonymous type.
var map =
Enumerable.Range(1,10).
Select(x => new { Id = x, Value = x.ToString() }).
ToDictionary(x => x.Id);
The variable map is a Dicitonary<TKey,TValue>
where TValue
is an anonymous type. Enumerating the map will produce a KeyValuePair with the TValue
being the same anonymous type.
Should be able to use the .Remove(), .RemoveAt(), or one of the other methods.
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> kvp = list[i];
list.Remove(kvp);
or
list.Remove(list[1]);
You must obtain a reference to the object you want to remove - that's why I found the item I'm looking for and assigned to a KeyValuePair - since you're telling it to remove a specific item.
A better solution might be to use a dictionary:
Dictionary<string, string> d = new Dictionary<string, string>();
if (d.ContainsKey("somekey")) d.Remove("somekey");
This allows you to remove by the key value instead of having to deal with the list not being indexed by the key.
Edit you may not have to get a KeyValuePair reference first. Still, a dictionary is probably a better way to go.
To remove all items in the list by key:
myList.RemoveAll(x => x.Key.Equals(keyToRemove));
Here are a few examples of removing an item from a list of KeyValuePair:
// Remove the first occurrence where you have key and value
items.Remove(new KeyValuePair<int, int>(0, 0));
// Remove the first occurrence where you have only the key
items.Remove(items.First(item => item.Key.Equals(0)));
// Remove all occurrences where you have the key
items.RemoveAll(item => item.Key.Equals(0));
EDIT
// Remove the first occurrence where you have the item
items.Remove(items[0]);