我已经读了this question篇关于为什么不可能的文章,但还没有找到解决问题的方法.

我想从.NET HashSet<T>检索一个项目.我正在寻找一种具有此签名的方法:

/// <summary>
/// Determines if this set contains an item equal to <paramref name="item"/>, 
/// according to the comparison mechanism that was used when the set was created. 
/// The set is not changed. If the set does contain an item equal to 
/// <paramref name="item"/>, then the item from the set is returned.
/// </summary>
bool TryGetItem<T>(T item, out T foundItem);

使用这种方法在集合中搜索一个项将是O(1).从HashSet<T>中检索项目的唯一方法是枚举O(n)的所有项目.

我还没有找到解决这个问题的方法,除了自己制作HashSet<T>或使用Dictionary<K, V>.还有其他 idea 吗?

Note:

推荐答案

你要的是.NET Core a year ago,是recently added to .NET 4.7.2:

在里面NET Framework 4.7.2我们在标准集合类型中添加了一些API,这些API将支持以下新功能

签名如下(可在.NET 4.7.2及更高版本中找到):

    //
    // Summary:
    //     Searches the set for a given value and returns the equal value it finds, if any.
    //
    // Parameters:
    //   equalValue:
    //     The value to search for.
    //
    //   actualValue:
    //     The value from the set that the search found, or the default value of T when
    //     the search yielded no match.
    //
    // Returns:
    //     A value indicating whether the search was successful.
    public bool TryGetValue(T equalValue, out T actualValue);

P.S.:如果你感兴趣,这里有related function they're adding in the future个哈希集.盖托拉德(T).

.net相关问答推荐

API响应返回null错误. NET MAUI

";Make Async ValueTask/ValueTask方法分期分配发生了什么?

为什么Regex.Escape支持数字符号和空格?

从窗体中移除另一个控件中引用的控件时获取设计时通知

在本地运行 Azure 函数会在 .NET7 升级后出现无运行时错误

信号量的多线程问题

当 Func 委托需要接口作为参数时,它是如何工作的?

每当属性值发生变化时引发事件?

IIS Express - 500.19 无法读取配置文件 - 因为它正在查看错误的路径

是否有用于 Windows / C# 开发的可嵌入 Webkit 组件?

什么是 SUT,它来自哪里?

DateTime.TryParseExact() 拒绝有效格式

如何结合 ||条件语句中的运算符

无法在 Windows 10 上安装 Windows SDK 7.1

我应该在 LINQ 查询中使用两个where子句还是&&?

Convert.ToBoolean 和 Boolean.Parse 不接受 0 和 1

迭代器和枚举器的区别

如何对 LINQ to XML 中的元素进行深层复制?

C#/.NET 中仅命名空间的类可见性?

从不同程序集中的类名中解析类型