根据值删除字典中的项目 [英] Remove Item in Dictionary based on Value

查看:23
本文介绍了根据值删除字典中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典<字符串,字符串>.

我需要在该字典中查看基于其他地方输入的值是否存在,如果存在则将其删除.

I need to look within that dictionary to see if a value exists based on input from somewhere else and if it exists remove it.

ContainsValue 只是说真/假,而不是该项目的索引或键.

ContainsValue just says true/false and not the index or key of that item.

帮助!

谢谢

刚刚发现这个 - 你觉得怎么样?

Just found this - what do you think?

var key = (from k in dic where string.Compare(k.Value, "two", true) ==
0 select k.Key).FirstOrDefault();

编辑 2:我也刚刚敲了这个可能有用

EDIT 2: I also just knocked this up which might work

foreach (KeyValuePair<string, string> kvp in myDic)
{
    if (myList.Any(x => x.Id == kvp.Value))
        myDic.Remove(kvp.Key);
}

推荐答案

您是要删除单个值还是所有匹配的值?

Are you trying to remove a single value or all matching values?

如果您要删除单个值,您如何定义要删除的值?

If you are trying to remove a single value, how do you define the value you wish to remove?

在查询值时没有取回键的原因是字典可能包含与指定值配对的多个键.

The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.

如果你想删除所有相同值的匹配实例,你可以这样做:

If you wish to remove all matching instances of the same value, you can do this:

foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
    dic.Remove(item.Key);
}

如果你想删除第一个匹配的实例,你可以查询找到第一项并删除它:

And if you wish to remove the first matching instance, you can query to find the first item and just remove that:

var item = dic.First(kvp => kvp.Value == value);

dic.Remove(item.Key);

注意:ToList() 调用是将值复制到新集合所必需的.如果未进行调用,循环将修改它正在迭代的集合,从而导致在删除第一个值后下次尝试迭代时抛出异常.

Note: The ToList() call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.

这篇关于根据值删除字典中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆