检查项目是否不在keyvaluepair列表中

时间:2015-12-01 18:10:05

标签: c# .net linq list keyvaluepair

我有一个List<KeyValuePair<string, bool>>类型的列表。此列表包含8个项目。我还有一个字符串line。我试图检查line是否包含来自TKey(字符串)的单词且TValue是否为假。

我没有使用字典,因为lst可能包含重复项。

如果line不包含任何相应TKey为false的TValue,则应该为真。

似乎AnyAll都不符合我的需求:

if (lst.Any(x => !line.Contains(x.Key) && x.Value == false)
{
   // this is always true even if line does contain a TKey.
   // I'm not exactly sure why.
}

if (lst.All(x => !line.Contains(x.Key) && x.Value == false)
{
   // this is always false even if line does not contain a TKey.
   // I think it would only be true if line contained *every* TKey?
}

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是通过过滤Value来检查目标false中是否缺少string p.Value的所有字词:

if (list.Where(p => !p.Value).All(w => !line.Contains(x.Key))) {
    ...
}

您还可以修复查询:

if (lst.All(x => !line.Contains(x.Key) || x.Value) {
    ...
}

这要求对于每个KVP,至少有以下一种情况属实:

  • 行不包含密钥,或
  • 值为true

答案 1 :(得分:2)

这应该对你有用

if (!lst.Any(x => line.Contains(x.Key) && !x.Value))
{
   //line does not contain any TKey where the corresponding TValue is false
}