如何检查字典中是否已存在一组键和值 [英] How to check if a set of key and value already exists in a dictionary

查看:144
本文介绍了如何检查字典中是否已存在一组键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 dictionary.Add( 1  一个); 
dictionary.Add( 1 one );





dictionary.Add(1,one); //如何在添加到字典之前检查我想要检查的字典中是否已存在以下键和值对是否

如果

{

(1,一);如果下面的一组键值不合适

dictionary.ADD(1,one);



}



我的尝试:



如何检查如果以下一对密钥且已存在  a 

解决方案

查看方法:Dictionary(TKey,TValue)方法(System.Collections.Generic) [ ^ ]


正如您可能已经发现的那样,如果您添加(密钥,值)字典已经有一个具有相同键的条目,它会抛出 ArgumentException 。不可能有多个条目具有相同的

如果要在密钥不存在时添加值,请尝试此操作:

字典< int,string> dict =  new  Dictionary< int,string>(); 
// 演示的初始值
dict.Add( 1 umpteen);
dict.Add( 2 di );
// 稍后
if (!dict.Contains( 1 ))
dict.Add( 1 mono);
// dict中没有任何变化
if (!dict.Contains( 3 ))
dict.Add( 3 three);
// 添加了新的键值对



如果您只想确保字典中存在键值对,则无论是否存在已经键值对具有相同的并且具有相同或不同的值,而不是添加转到字典,只需分配到它:

  / /  假设dict,因为我们将其保留在上面...  
dict [ 1 ] = mono;
dict [ 2 ] = di ;
dict [ 3 ] = tri ;
dict [ 4 ] = quad ;



这些分配都没有引发异常,并且 dict 中的所有4个条目都已设置。


您可以使用以下方法检查密钥是否存在

 ContainsKey(TKey)





这是检查一个值

 ContainsValue(TValue)


dictionary.Add(1,"one");
dictionary.Add(1,"one");



dictionary.Add(1,"one"); //how to check if following pair of key and value already exists in a dictionery i want to check before Adding to the dictionary
if
{
(1,"one"); if following set of key value do not exixts
dictionary.ADD(1,"one");

}

What I have tried:

how to check if following pair of key and value already exists in a 

解决方案

Check out the methods: Dictionary(TKey, TValue) Methods (System.Collections.Generic)[^]


As you've probably discovered, if you Add(key, value) to a Dictionary that already has an entry with the same key, it throws an ArgumentException. It is not possible to have multiple entries with the same key.
If you want to add the value if the key is not present then try this:

Dictionary<int, string> dict = new Dictionary<int, string>();
// initial value for demonstration
dict.Add(1, "umpteen");
dict.Add(2, "di");
// later
if (!dict.Contains(1))
  dict.Add(1, "mono");
// nothing changed in dict
if (!dict.Contains(3))
  dict.Add(3, "three");
// A new key-value pair was added


If all you want it to ensure that a key-value pair exists in the Dictionary, no matter if there is already a key-value pair with the same key and either the same or a different value, then instead of Adding to the Dictionary, just assign into it:

// assume dict as we left it above...
dict[1] = "mono";
dict[2] = "di";
dict[3] = "tri";
dict[4] = "quad";


None of those assignments threw an exception and all 4 entries in the dict are set.


You can use below method to check whether a key is exist or not

ContainsKey(TKey)



And this to check a value

ContainsValue(TValue)


这篇关于如何检查字典中是否已存在一组键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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