我有一个List<KeyValuePair<string, bool>>
类型的列表。此列表包含8个项目。我还有一个字符串line
。我试图检查line
是否包含来自TKey
(字符串)的单词且TValue
是否为假。
我没有使用字典,因为lst
可能包含重复项。
如果line
不包含任何相应TKey
为false的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?
}
有办法做到这一点吗?
答案 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
}