gpt4 book ai didi

c# - 如何从 HashSet 中检索实际项目?

转载 作者:IT王子 更新时间:2023-10-29 03:41:23 24 4
gpt4 key购买 nike

我读过 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> .还有其他想法吗?

注意:
我不想检查 HashSet<T> 是否包含项目。我想获取对存储在 HashSet<T> 中的项目的引用因为我需要更新它(而不用另一个实例替换它)。我将传递给 TryGetItem 的项目会相等(根据我传递给构造函数的比较机制)但它不会是相同的引用。

最佳答案

这实际上是集合集合中的一个巨大遗漏。您可能只需要一个键字典或一个允许检索对象引用的哈希集。这么多人要求它,为什么它没有得到修复超出了我的范围。

如果没有第三方库,最好的解决方法是使用 Dictionary<T, T>键与值相同,因为 Dictionary 将其条目存储为哈希表。在性能方面它与 HashSet 相同,但它当然会浪费内存(每个条目的指针大小)。

Dictionary<T, T> myHashedCollection;
...
if(myHashedCollection.ContainsKey[item])
item = myHashedCollection[item]; //replace duplicate
else
myHashedCollection.Add(item, item); //add previously unknown item
...
//work with unique item

关于c# - 如何从 HashSet<T> 中检索实际项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7760364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com