How can I remove a item from list of KeyValuePair?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With