How can one check if a key/value pair exists in a Dictionary<TKey,TValue>
? I'm able to check if a key or value exist, using ContainsKey
and ContainsValue
, but I'm unsure of how to check if a key/value pair exist.
Well the pair can't exist if the key doesn't exist... so fetch the value associated with the key, and check whether that's the value you were looking for. So for example:
// Could be generic of course, but let's keep things simple...
public bool ContainsKeyValue(Dictionary<string, int> dictionary,
string expectedKey, int expectedValue)
{
int actualValue;
if (!dictionary.TryGetValue(expectedKey, out actualValue))
{
return false;
}
return actualValue == expectedValue;
}
Or slightly more "cleverly" (usually something to avoid...):
public bool ContainsKeyValue(Dictionary<string, int> dictionary,
string expectedKey, int expectedValue)
{
int actualValue;
return dictionary.TryGetValue(expectedKey, out actualValue) &&
actualValue == expectedValue;
}
A dictionary only supports one value per key, so:
// key = the key you are looking for
// value = the value you are looking for
YourValueType found;
if(dictionary.TryGetValue(key, out found) && found == value) {
// key/value pair exists
}
if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
return true;
You can do this by using dictionary.TryGetValue.
Dictionary<string, bool> clients = new Dictionary<string, bool>();
clients.Add("abc", true);
clients.Add("abc2", true);
clients.Add("abc3", false);
clients.Add("abc4", true);
bool isValid = false;
if (clients.TryGetValue("abc3", out isValid)==false||isValid == false)
{
Console.WriteLine(isValid);
}
else
{
Console.WriteLine(isValid);
}
At the above code if condition there is two sections first one for checking key has value and second one for comparing the actual value with your expected value.
First Section{clients.TryGetValue("abc3", out isValid)==false}||Second Section{isValid == false}
Simple, Generic Extension Method
Here's a quick generic extension method that adds a ContainsPair()
method to any IDictionary
:
public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue value)
{
return dictionary.TryGetValue(key, out var found) && found.Equals(value);
}
This allows you to do checks against dictionaries like this:
if( myDict.ContainsPair("car", "mustang") ) { ... } // NOTE: this is not case-insensitive
Case-Insensitive Check
When working with string-based keys, you can make the Dictionary
case-insensitive with regard to its keys by creating it with a comparer such as StringComparer.OrdinalIgnoreCase
when the dictionary is constructed.
However, to make the value comparison case insensitive (assuming the values are also strings), you can use this version that adds an IComparer
parameter:
public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue value,
IComparer<TValue> comparer)
{
return dictionary.TryGetValue(key, out var found) && comparer.Compare(found, value) == 0;
}
Generic version of Jon Skeet's answer
public bool ContainsKeyValue<TKey, TVal>(Dictionary<TKey, TVal> dictionnaire,
TKey expectedKey,
TVal expectedValue) where TVal : IComparable
{
TVal actualValue;
if (!dictionnaire.TryGetValue(expectedKey, out actualValue))
{
return false;
}
return actualValue.CompareTo(expectedValue) == 0;
}
How something like this
bool exists = dict.ContainsKey("key") ? dict["key"] == "value" : false;
var result= YourDictionaryName.TryGetValue(key, out string value) ? YourDictionaryName[key] : "";
If the key is present in the dictionary, it returns the value of the key otherwise it returns a blank object.
Hope, this code helps you.
This functionality is already available out of the box, but it's hidden in the Contains
method of the ICollection<KeyValuePair<TKey, TValue>>
interface, which the Dictionary<TKey,TValue>
class implements. Here is how it can be exposed as a public
extension method:
public static bool Contains<TKey, TValue>(this Dictionary<TKey, TValue> dictionary,
TKey key, TValue value)
{
ArgumentNullException.ThrowIfNull(dictionary);
return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Contains(new(key, value));
}
First you check if the key exists, if so, you get the value for this key and compare it to the value you are testing... If they are equal, your Dictionary contains the pair
Please check with following code
var dColList = new Dictionary<string, int>();
if (!dColList.Contains(new KeyValuePair<string, int>(col.Id,col.RowId)))
{}
Thanks, Mahesh G
Dictionary<TKey,TValue>
does not have a Contains
method. This is using the LINQ extension of IEnumerable<T>
that does a linear search of the sequence, and is not able to use the dictionary's ability to look up a key based on it's hash. There are numerous other answers here that do this correctly using actual methods of the dictionary that leverage it's fast searching. –
Johathan int i = FindEntry(keyValuePair.Key);
. It first does lookup for key and then compares the value if(i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
. It doesn't use linear search. –
Balough ICollection.Contains
. This is calling the LINQ Contains method. –
Johathan Dictionary
class implements interface IDictionary<TKey, TValue>
which extends ICollection<KeyValuePair<TKey, TValue>>
and the method signature is bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
. Therefore the Dictionary
class implements the interface method and it will be called. –
Balough © 2022 - 2024 — McMap. All rights reserved.
found
in one expression. – Tanker