c# - Using HashSet and Contains to return TRUE if one or many fields is in the hash -


i wondering if possible use hashset , make method contains return true if 1 of field in hash giving object.

this example of like

static void main(string[] args) {     hashset<product> hash = new hashset<product>();      // since id same, both products considered same if uri not same     // opposite true.  if uri same, both products considered same if id not same     product product1 = new product("123", "www.test.com/123.html");     product product2 = new product("123", "www.test.com/123.html?lang=en");      hash.add(product1);      if (hash.contains(product2))     {         // want method "contains" return true because 1 of field in hash     } } 

here definition of class product

public class product {     public string webid     public string uri      public product(string id, string uri)     {         webid = id;         uri = uri;     }      public override bool equals(object obj)     {         if (referenceequals(null, obj)) return false;         if (referenceequals(this, obj)) return true;         if (obj.gettype() != typeof(product)) return false;         return equals((product)obj);     }      public bool equals(product obj)     {         if (referenceequals(null, obj)) return false;         if (referenceequals(this, obj)) return true;          if (string.equals(webid, obj.webid) || string.equals(uri, obj.uri))              return true;         else             return false;     }      public override int gethashcode()     {         unchecked         {             int hash = 17;              hash = hash * 23 + webid.gethashcode();             hash = hash * 23 + uri.gethashcode();             return hash;         }     } } 

when run program, method contains runs gethashcode , never method equals. hence, method contains return false.

how can make hashset return true example above ? should using dictionary instead , add each fields dictionary ?

your gethashcode() implementation isn't guaranteed return same value 2 objects equal. since require match on, say, webid. uri screws hash code. or other way around. cannot fix this, other returning 0. that's going kill hashset<> perf, lookup o(n) instead of o(1).


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -