简体   繁体   中英

C#: Using ContainsKey where the keys are objects

Ok so I need a bit of help. I have a generic dictionary "cashdata". The keys of this dictionary are objects (Query objects, a class I have defined). Query objects have "Terms" field, which is a list of strings, and an "Operator" field, which is an enum (Either "All" or "Any").

cashdata.ContainsKey(a_query_object);

And have it yield true or false depending on if a_query_object and an object in the dictionary are identical in terms of their Terms and Operator. What is the best way to do this? A HashCode possibly? I would appreciate an example, thanks in advance.

EDIT: cashdata Dictionary is defined as such

Dictionary<Query,List<string> > cashData = new Dictionary<Query,List<string>>();

Make your object implement IEquatable Interface along with overriding Object.Equals and GetHashCode as mentioned in the remarks section in MSDN

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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