基于价值的字典中删除项目 [英] Remove Item in Dictionary based on Value

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

问题描述

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

我需要看的字典中,看是否有存在的价值基于输入从别的地方,如果它存在,将其删除。

中的containsValue只是说真/假,而不是索引或该项目的关键。

帮助!

感谢

编辑:刚刚发现这一点 - 你有什么感想

  VAR键=(从K的DIC在那里的String.Compare(k.Value,二,真)==
0选择k.Key).FirstOrDefault();
 

编辑2:我也只是被撞这件事可能正常工作

 的foreach(KeyValuePair<字符串,字符串> KVP在myDic)
{
    如果(myList.Any(X => x.Id == kvp.Value))
        myDic.Remove(kvp.Key);
}
 

解决方案

您试图删除一个值或全部匹配值?

如果你想删除一个单一的价值,你怎么定义的值要删除?

你没有得到一个关键的回值查询时,其原因是因为字典可能包含搭配指定的值的多个键。

如果您要删除的相同值的所有匹配的情况下,你可以这样做:

 的foreach(在dic.Where VAR项目(KVP => kvp.Value ==值).ToList())
{
    dic.Remove(item.Key);
}
 

如果你想删除第一个匹配的情况下,您可以查询到找到的第一个项目,只是删除:

  VAR项目= dic.First(KVP => kvp.Value ==值);

dic.Remove(item.Key);
 

注意:了ToList()调用需要的值复制到一个新的集合。如果呼叫不进行,环​​路将修改它遍历集合,引起异常在下次尝试来迭代第一值被除去后的抛出。

I have a Dictionary<string, string>.

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 just says true/false and not the index or key of that item.

Help!

Thanks

EDIT: 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();

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

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天全站免登陆