Check key / value pair in list

I have a list declared as

 List<KeyValuePair<string, Int64>> KPList = new List<KeyValuePair<string, long>>(); 

I need to check if a combination of key and value exists. I can’t use the dictionary, because I need to have a unique combination of key and value, where in case the key has several values, but as one pair

if(!KPList.Any(p=> p.Key ==keyp && p.Value == valuep))

What's bad about it?

+4
source share
2 answers

You can also use a HashSet that does not matter, but works as needed.

HashSet< Tuple<string, long> > KPSet = new HashSet< Tuple<string, long> >(); 
...
if(KPSet.Contains(p))
{
    ...
}
+4
source

For ease of use and better performance, I would suggest using a combination of Dictionary and HashSet:

var KPDict = new Dictionary<string, HashSet<long>>();

Then it will provide you with the search complexity of O (1) + O (1) and a convenient check of the value:

if (KPDict.ContainsKey(keyp) && KPDict[keyp].Contains(valuep)) {
    //do some actions
}
else{
    //some logic in case keyp, valuep pair not found in KPDict
}
+1
source

All Articles