我已经读过这个问题,为什么它不可能,但没有找到问题的解决方案.
我想从.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);
Run Code Online (Sandbox Code Playgroud)
使用这种方法搜索集合的项目将是O(1).从a中检索项目的唯一方法HashSet<T>是枚举所有O(n)项.
除了自己制作HashSet<T>或使用之外,我还没有找到解决这个问题的方法Dictionary<K, V>.还有其他想法吗?
注意:
我不想检查是否HashSet<T> …
我需要向Set添加很多对象.我应该非常快速地检索它们.我知道的唯一方法是使用哈希.但是C#中的HashSet类不包含任何"Get"方法.字典类没有用,因为在字典中查找对象非常耗时.
A HashSet<T>可以在O(1)中确定它是否包含某个项目.如果我覆盖Equals()并GetHashCode()在我的自定义类上,我可以有一个对象A和另一个对象A',它们不相同,但是Equals()返回true并GetHashCode()返回相同的哈希码.
现在,假设A在哈希集中,我想在给定A'的O(1)中检索A(从哈希集的角度看它等于A).
var a = new MyClass("A");
var a_prime = new MyClass("A");
Debug.Assert(a.Equals(a_prime));
Debug.Assert(a.GetHashCode() == a_prime.GetHashCode());
var set = new HashSet<MyClass>();
set.Add(a);
Debug.Assert(set.Contains(a_prime));
// This:
var retrieved_a = set.Get(a_prime);
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
一些背景信息:我想使用set来实习我自己的对象,就像C#interns strings一样:等于对象只需要一个实例.通过这种方式,我可以将元数据附加到这样的对象,并确保没有该元数据,在任何地方都没有其他相同的实例.
我有这种情况,其中内存保护是至关重要的.我试图将> 1 GB的肽序列读入共享相同序列的记忆和组肽实例中.我将Peptide对象存储在Hash中,因此我可以快速检查重复,但发现即使知道Set包含该对象,也无法访问Set中的对象.
内存非常重要,如果可能,我不想复制数据.(否则我会将我的数据结构设计为:peptides = Dictionary<string, Peptide>但是会复制字典和Peptide类中的字符串).下面是代码,向您展示我想要完成的任务:
public SomeClass {
// Main Storage of all the Peptide instances, class provided below
private HashSet<Peptide> peptides = new HashSet<Peptide>();
public void SomeMethod(IEnumerable<string> files) {
foreach(string file in files) {
using(PeptideReader reader = new PeptideReader(file)) {
foreach(DataLine line in reader.ReadNextLine()) {
Peptide testPep = new Peptide(line.Sequence);
if(peptides.Contains(testPep)) {
// ** Problem Is Here **
// I want to get the Peptide object that is in HashSet
// so I can add the …Run Code Online (Sandbox Code Playgroud) C#的通用HashSet <T>搜索性能应该是O(1),并且ObservableCollection <T>的搜索性能应该是O(n).
我有大量的唯一元素,每个元素都有一个不唯一的DateTime属性.
每个元素只需返回其DateTime.GetHashCode()即可计算其HashCode.
现在我想得到我的数据的一个子集,例如,所有元素的日期都在2012年3月到2012年6月之间.
var result = from p in this.Elements
where p.Date >= new DateTime(2012, 03, 01) &&
p.Date <= new DateTime(2012, 30, 06
select p;
Run Code Online (Sandbox Code Playgroud)
如果我在300.000个元素的集合上运行此LINQ查询,则返回给定范围内的80个元素需要大约25毫秒 - 如果我使用HashSet <T>或ObservableCollection <T>则无关紧要.
如果我手动遍历所有元素并检查它们,则需要相同的时间,约25毫秒.
但我确实知道在给定范围内的所有日期的HashCode.是否可以从我的HashSet <T>获取具有给定HashCodes的所有元素?我觉得那会快得多......
是否可以加快LINQ查询?我假设它没有利用我的HashSet <T>的特殊能力?