c# - 在两个 HashSet 中搜索

标签 c# search hashset

我有这个方法:

bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle) {
}

我正在尝试执行以下操作:如果 hayStack1hayStack2 均为 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 Or s1 == 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/

相关文章:

c++ - 字符串选择排序 C++

c# - 在 C# 中将多个参数传递给 Func<>

c# - 执行以下C#代码时出错

html - 如何标记 chrome 的搜索框以在其 "Other search engines"中检测和安装?

search - 有人知道免费网站搜索吗?

hash - 如何为 HashSet<T> 实现哈希?

Nim-lang 中的哈希集

c# - Linq - 从另一个列表中删除一个匿名列表

c# - Microsoft.Extensions.Logging 记录器包装器的实现和使用

java - 为什么 HashSet 没有构建 Set 接口(interface)的所有方法