简体   繁体   中英

C# - Remove a item from list of KeyValuePair

如何从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.

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]);

要按键删除列表中的所有项目:

myList.RemoveAll(x => x.Key.Equals(keyToRemove));

应该能够使用.Remove(),. RemoveAt()或其他方法之一。

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM