Csharp/C#教程:如何在不枚举的情况下访问HashSet 的引用值?分享


如何在不枚举的情况下访问HashSet 的引用值?

我有这种情况,其中内存保护是至关重要的。 我试图将> 1 GB的肽序列读入共享相同序列的记忆和组肽实例中。 我将Peptide对象存储在Hash中,因此我可以快速检查重复,但发现即使知道Set包含该对象,也无法访问Set中的对象。

内存非常重要,如果可能,我不想复制数据。 (否则我会将我的数据结构设计为:peptides = Dictionary但这会复制字典和Peptide类中的字符串)。 下面是代码,向您展示我想要完成的任务:

 public SomeClass { // Main Storage of all the Peptide instances, class provided below private HashSet peptides = new HashSet(); public void SomeMethod(IEnumerable 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 DataLine to it, I don't want use the // testPep object (even though they are considered "equal") peptides[testPep].Add(line); // I know this doesn't work testPep.Add(line) // THIS IS NO GOOD, since it won't be saved in the HashSet which i use in other methods. } else { // The HashSet doesn't contain this peptide, so we can just add it testPep.Add(line); peptides.Add(testPep); } } } } } } public Peptide : IEquatable { public string Sequence {get;private set;} private int hCode = 0; public PsmList PSMs {get;set;} public Peptide(string sequence) { Sequence = sequence.Replace('I', 'L'); hCode = Sequence.GetHashCode(); } public void Add(DataLine data) { if(PSMs == null) { PSMs = new PsmList(); } PSMs.Add(data); } public override int GethashCode() { return hCode; } public bool Equals(Peptide other) { return Sequence.Equals(other.Sequence); } } public PSMlist : List { // and some other stuff that is not important } 

为什么HashSet不让我获得HashSet中包含的对象引用? 我知道人们会试着说如果HashSet.Contains()返回true,你的对象是等价的。 它们在值方面可能是等价的,但我需要引用相同,因为我在Peptide类中存储了其他信息。

我想出的唯一解决方案是Dictionary ,其中键和值都指向相同的参考。 但这似乎很俗气。 是否有其他数据结构可以实现此目的?

基本上你可以自己重新实现HashSet ,但这是我所知道的唯一解决方案。 DictionaryDictionary解决方案可能效率不高 – 如果你每个条目只浪费一个参考,我想这将是相对无关紧要的。

实际上,如果从Peptide删除hCode成员,那么每个对象将保护4个字节,这与x86中的引用大小相同……就我所知,缓存哈希是没有意义的。只会计算每个对象的哈希值,至少在您显示的代码中。

如果你真的非常渴望记忆,我怀疑你可以比string更有效地存储序列。 如果您向我们提供有关序列所包含内容的更多信息,我们可以在那里提出一些建议。

我不知道为什么HashSet不允许这样做有任何特别强烈的理由 ,除了它是一个相对罕见的要求 – 但它是我在Java中看到的要求……

使用Dictionary

上述就是C#学习教程:如何在不枚举的情况下访问HashSet 的引用值?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1015669.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐