Jar*_*Par 18
如果您同时拥有密钥和值,则可以执行以下操作
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));
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为KeyValuePair<TKey,TValue>
不会覆盖Equality但是是一个结构.这意味着它使用默认值相等.这只是比较字段的值来测试相等性.所以你只需要创建一个KeyValuePair<TKey,TValue>
具有相同字段的新实例.
编辑
为了回应评论者,扩展方法在这里提供了什么价值?
在代码中最好看到理由.
list.Remove(new KeyValuePair<int,string>(key,value));
list.Remove(key,value);
Run Code Online (Sandbox Code Playgroud)
此外,在键或值类型是匿名类型的情况下,需要扩展方法.
EDIT2
以下是如何获取KeyValuePair的示例,其中2个中的一个具有匿名类型.
var map =
Enumerable.Range(1,10).
Select(x => new { Id = x, Value = x.ToString() }).
ToDictionary(x => x.Id);
Run Code Online (Sandbox Code Playgroud)
变量映射是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));
Run Code Online (Sandbox Code Playgroud)
编辑
// Remove the first occurrence where you have the item
items.Remove(items[0]);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18031 次 |
最近记录: |