1

I have a

  var  itemList = new List<Item>() 

and a

  var  searchSet = new HashSet<TestItem>(new TestItemComparer());

For each element in the itemList I look for its existance in the searchSet via the Number property.

I search like this: ( The item.Numer is an enumerated element of the itemList)

var isFound = searchSet.Contains(new TestItem{ Number = item.Numer });

 public class TestItemComparer: IEqualityComparer<TestItem>
    {
        public bool Equals(TestItem x, TestItem y)
        {
            return x.Number == y.Number;
        }

        public int GetHashCode(TestItem obj)
        {
            return obj.Number.GetHashCode();
        }
    }

The reason why my searchSet has a comlex type TestItem and not integer is because I still want to combine my search with some other properties on the TestItem class.

How can I still use this amazing fast HashSet.Contains method but combine the Number search with other properties?

Should I change my TestItemComparer for this?

Elisabeth
  • 20,496
  • 52
  • 200
  • 321
  • 2
    See this question: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode – Peter B Dec 09 '16 at 08:09
  • I agree with Peter that the duplicate is actually the best answer. Just update your `GetHashCode` and you will be fine. – Patrick Hofman Dec 09 '16 at 08:11

1 Answers1

2

Yes you can. Just add other properties to your Equals and GetHashCode methods.

public class TestItemComparer: IEqualityComparer<TestItem>
{
    public bool Equals(TestItem x, TestItem y)
    {
        return x.Number == y.Number && x.Something == y.Something;
    }

    public int GetHashCode(TestItem obj)
    {
        return obj.Number ^ obj.Something;
    }
}

Check this thread Implementing GetHashCode to see whats the best way to implement GetHashCode

Community
  • 1
  • 1
Konrad Lalik
  • 596
  • 4
  • 8
  • Your link contains another link which is the same as Perter B`s link :P How would then the Contains(new TestItem { ??? }); call look like? and what if the additional properties is just one more property but I search for 2 different values like TestIte.State == "blue" || "black". How is that done in the Comparer? – Elisabeth Dec 09 '16 at 08:34
  • Contains(new TestItem {Number = item.Numer, State = item.State }). Comparer should compare two objects and nothing more, so I think that if you want to find element with State == "blue" and "black" you should call Contains method twice. Implementing Comparer in any "unusual" way can lead to obscure code – Konrad Lalik Dec 09 '16 at 09:19