如何检查字典中是否已存在一组键和值 [英] How to check if a set of key and value already exists in a dictionary
问题描述
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 youAdd(key, value)
to aDictionary
that already has an entry with the samekey
, it throws anArgumentException
. It is not possible to have multiple entries with the samekey
.
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 theDictionary
, no matter if there is already a key-value pair with the same key and either the same or a different value, then instead ofAdd
ing to theDictionary
, 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 thedict
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屋!