Skip to main content
 首页 » 编程设计

c#之检查项目是否不在键值对列表中

2024年02月05日12www_RR

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

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

如果 line 这应该是真的不包含任何 TKey其中对应的TValue是假的。

Any 似乎都没有也不All在这里适合我的需要:

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? 
} 

有办法吗?

请您参考如下方法:

一种方法是用 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