简体   繁体   English

在给定对象y的情况下,我可以在散列集中检索存储的值x,其中x.Equals(y)

[英]Can I retrieve the stored value x in a hashset given an object y where x.Equals(y)

[TestFixture]
class HashSetExample
{
    [Test]
    public void eg()
    {
        var comparer = new OddEvenBag();
        var hs = new HashSet<int>(comparer);

        hs.Add(1);

        Assert.IsTrue(hs.Contains(3));
        Assert.IsFalse(hs.Contains(0));

        // THIS LINE HERE
        var containedValue = hs.First(x => comparer.Equals(x, 3)); // i want something faster than this
        Assert.AreEqual(1, containedValue);
    }

    public class OddEvenBag : IEqualityComparer<int>
    {
        public bool Equals(int x, int y)
        {
            return x % 2 == y % 2;
        }

        public int GetHashCode(int obj)
        {
            return obj % 2;
        }
    }
}

As well as checking if hs contains an odd number, I want to know what odd number if contains. 除了检查是否HS包含奇数个,我想知道什么是奇数,如果包含。 Obviously I want a method that scales reasonably and does not simply iterate-and-search over the entire collection. 显然,我想要一种合理扩展的方法,而不是简单地迭代和搜索整个集合。

Another way to rephrase the question is, I want to replace the line below THIS LINE HERE with something efficient (say O(1), instead of O(n)). 另一种重新解释这个问题的方法是,我想用一些有效的东西(比如O(1),而不是O(n))替换THIS LINE HERE下面的一行。

Towards what end? 到底是什么? I'm trying to intern a laaaaaaaarge number of immutable reference objects similar in size to a Point3D. 我正在尝试实现一个与Point3D大小相似的laaaaaaarge数量的不可变引用对象。 Seems like using a HashSet<Foo> instead of a Dictionary<Foo,Foo> saves about 10% in memory. 似乎使用HashSet<Foo>而不是Dictionary<Foo,Foo>在内存中节省了大约10%。 No, obviously this isn't a game changer but I figured it would not hurt to try it for a quick win. 不,显然这不是游戏改变者,但我认为尝试快速获胜并不会有什么坏处。 Apologies if this has offended anybody. 如果这冒犯了任何人,请道歉。

Edit: Link to similar/identical post provided by Balazs Tihanyi in comments, put here for emphasis. 编辑: 链接到 Balazs Tihanyi在评论中提供的类似/相同的帖子 ,放在这里强调。

The simple answer is no, you can't. 简单的答案是否定的,你不能。

If you want to retrieve the object you will need to use a HashSet . 如果要检索对象,则需要使用HashSet There just isn't any suitable method in the API to do what you are asking for otherwise. API中没有任何合适的方法来执行您要求的其他方法。

One optimization you could make though if you must use a Set for this is to first do a contains check and then only iterate over the Set if the contains returns true. 如果你必须使用一个Set ,你可以做的一个优化是首先进行contains检查,然后只有当包含返回true时迭代Set Still you would almost certainly find that the extra overhead for a HashMap is tiny (since essentially it's just another object reference). 你几乎肯定会发现HashMap的额外开销很小(因为它本质上只是另一个对象引用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM