C# - Remove a item from list of KeyValuePair

c#, list

Solution

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.

Problem

How can I remove a item from list of KeyValuePair?

Original source