我已经读了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相关问答推荐

找不到包Microsoft.VisualStudio.Azure.Containers.Tools.Targets

.NET最小API BadRequest响应不返回正文

.Net MAUI Android 无法与 API localhost 对话

在.NET C#中截断整个单词的字符串

为什么这个多态 C# 代码会打印它的功能?

value 的默认参数必须是编译时间常数?

发布版本中的 Debug.WriteLine

添加新实体标量时实体框架 4 映射片段错误

为什么需要 XmlNamespaceManager?

如何判断对象是否是某种类型的数组?

如何使用反射在 .NET 中调用重载方法

您可以在 C# 代码中捕获本机异常吗?

我们应该总是在类中包含一个默认构造函数吗?

公钥令牌的作用是什么?

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

单元测试 C# 保护方法

Visual Studio 类图不显示关系

微软内部 PriorityQueue 中的错误?

静态方法继承的正确替代方法是什么?

在 .NET 中,null 的哈希码是否应该始终为零