我有这个方法:
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle) {
}
我正在尝试执行以下操作:如果 hayStack1
和 hayStack2
均为 null
该方法应返回 true
,如果其中一个不为 null
,则 needle
应该位于其中以返回 true
,如果两者都不是 >null
needle
可以位于其中一个或两个中,true
。
我可以做到这一点,但我的方法很困惑,有什么方法可以优雅地做到这一点吗?
最佳答案
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle)
{
bool? s1 = hayStack1?.Contains(needle);
bool? s2 = hayStack2?.Contains(needle);
if (s1 ?? s2 ?? true) return true;
return s2 == true;
}
说明:
if (s1 ?? s2 ?? true)
仅在以下情况下变为 true:
s1 == s2 == null
Ors1 == true || (s1 == null && s2 == true)
return s2 == true;
由于 s1
可能变为 false,因此我们检查 s2
是否为 true。
可以用单个 return 语句替换。
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle)
{
bool? s1 = hayStack1?.Contains(needle);
bool? s2 = hayStack2?.Contains(needle);
return (s1 ?? s2 ?? true) || s2 == true;
}
关于c# - 在两个 HashSet 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086042/