Check key / value pair in List

3.5k views Asked by At

I have list declared as

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

I need to check if a combination of key and value already exists. I can't use dictionary since I need to have unique combination of key and value where in case a key will have multiple values but as a single pair

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

What is wrong in this?

2

There are 2 answers

17
nsamsonau On

You can also use HashSet, which doesn't have values, but works as you need.

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

For easy-use and best performance I would like to suggest use combination of Dictionary and HashSet :

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

Then it will provides you O(1)+O(1) lookup complexity and easy check of value:

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