繁体   English   中英

C# - 从KeyValuePair列表中删除一个项目

[英]C# - Remove a item from list of KeyValuePair

如何从KeyValuePair列表中删除项目?

如果您同时拥有密钥和值,则可以执行以下操作

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

这是有效的,因为KeyValuePair<TKey,TValue>不会覆盖Equality但是是一个结构。 这意味着它使用默认值相等。 这只是比较字段的值来测试相等性。 因此,您只需要创建一个具有相同字段的新KeyValuePair<TKey,TValue>实例。

编辑

为了回应评论者,扩展方法在这里提供了什么价值?

在代码中最好看到理由。

list.Remove(new KeyValuePair<int,string>(key,value));
list.Remove(key,value);

此外,在键或值类型是匿名类型的情况下,需要扩展方法。

EDIT2

以下是如何获取KeyValuePair的示例,其中2个中的一个具有匿名类型。

var map = 
  Enumerable.Range(1,10).
  Select(x => new { Id = x, Value = x.ToString() }).
  ToDictionary(x => x.Id);

变量映射是Dicitonary<TKey,TValue> ,其中TValue是匿名类型。 枚举地图将生成KeyValuePair,其中TValue是相同的匿名类型。

以下是从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));

编辑

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

要么

    list.Remove(list[1]);

您必须获取对要删除的对象的引用 - 这就是为什么我找到了我正在寻找并分配给KeyValuePair的项目 - 因为您告诉它删除特定项目。

更好的解决方案可能是使用字典:

    Dictionary<string, string> d = new Dictionary<string, string>();
    if (d.ContainsKey("somekey")) d.Remove("somekey");

这允许您通过键值删除,而不必处理未被键索引的列表。

编辑您可能不必先获得KeyValuePair引用。 不过,字典可能是更好的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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