Can I get the stored value of x in the hashset given by 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; } } } 

Besides checking if hs contains an odd number, I want to know which odd number contains. Obviously, I need a method that scales reasonably and doesn't just iterate and search the entire collection.

Another way to rephrase the question: I want to replace the line below THIS LINE HERE with something effective (say, O (1), not O (n)).

For what purpose? I try to put laaaaaa a large number of immutable reference objects similar in size to Point3D. It seems like using a HashSet<Foo> instead of Dictionary<Foo,Foo> saves about 10% in memory. No, obviously, this is not a change of game, but I decided that it would not hurt to try for a quick victory. I apologize if this offended anyone.

Edit: Link to a similar / identical post provided by Balazs Tihany in the comments, posted here for emphasis.

+3
collections c #
source share
1 answer

The simple answer is no, you cannot.

If you want to get an object, you will need a HashSet . There is no suitable method in the API to do what you ask otherwise.

You can do one optimization if you must use Set to do this, to first perform a contains check, and then iterate over only Set if contains returns true. However, you will almost certainly find that the extra overhead for HashMap is tiny (since, in fact, this is just another object reference).

+1
source share

All Articles