Sunday, 15 March 2015

c# - Creating a custom Key in a dictionary -



c# - Creating a custom Key in a dictionary -

this question has reply here:

using object generic dictionary key 3 answers

i'm new c# , i'm trying create custom key dictionary.

here how create class

public class imagekey { public int rid; public int eid; public int lid; public imagekey(int rid, int eid, int lid) { rid = rid; eid = eid; lid = lid; } public bool equals(imagekey x, imagekey y) { homecoming x.rid == y.rid && x.lid == y.lid && x.eid == y.eid; } public int gethashcode(imagekey obj) { int hash = 13; hash = (hash * 7) + obj.rid.gethashcode(); hash = (hash * 7) + obj.eid.gethashcode(); hash = (hash * 7) + obj.lid.gethashcode(); homecoming hash; } }

i utilize hashset that

hashset<imagekey> resourcesid = new hashset<imagekey>();

and dictionary

var enteries = new dictionary<imagekey, int>();

but statement fails containskey when iterate on , seek see if there matched key

imagekey key = new imagekey(rid, eid, lid); bool knownid = enteries.containskey(key); if (!knownid) { enteries.add(key, new igaentry()); }

you class needs override object.equals, implement iequatable<t> interface, or implement iequalitycomparer<t> , pass keycomparer dictionary's constructor. need override gethashcode method avoid unexpected behavior, make sure right

otherwise, class compared reference.

refer marc's reply here sample.

c# c#-3.0

No comments:

Post a Comment