检查列表

时间:2015-06-08 01:15:31

标签: c# list keyvaluepair

我将列表声明为

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

我需要检查密钥和值的组合是否已经存在。我不能使用字典,因为我需要具有键和值的唯一组合,以防密钥具有多个值但作为单个对

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

这有什么问题?

2 个答案:

答案 0 :(得分:4)

您也可以使用 HashSet ,它没有值,但可以根据需要使用。

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

答案 1 :(得分:1)

为了方便使用和最佳性能,我建议使用Dictionary和HashSet的组合:

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

然后它将为您提供O(1)+ O(1)查找复杂性并轻松检查值:

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