On Tue, 04 Nov 2008 05:10:00 -0800, Luigi <ci****************@inwind.it>
wrote:
Hi all,
I have a dictionary (C# 2.0) with an object (an instance of a class) for
the
key.
The class has only a "name" field.
dictionary<object, ...>
When I use ContainsKey property of the dictionary to check if an object
with
the same "name", it returns me false.
How can I check if an object with the same "name" field is already a key
in
my dictionary?
That depends.
Do you really want/need to use your object itself as the key for the
dictionary? If not, the solution is simple: just use the "name" as the
key, rather than the whole object.
If you have to use the object instance itself as the key, then the next
question is: do you want/expect for multiple instances of your key object
to be considered the same key when the "name" field is the same? If so
then one solution is to override Equals() and GetHashCode() in your
object's class. In those methods, just call the appropriate method
(Equals() and GetHashCode()) on the field in the two objects.
Another solution is to pass an implementation of IEqualityComparer<TKey>
to the Dictionary<TKey, TValueconstructor. See
http://msdn.microsoft.com/en-us/library/ms132072.aspx for more details.
If, on the other hand, you want to continue using your key object as it is
currently (that is...different instances are considered different keys),
then you'll simply have to enumerate the dictionary elements one by one,
comparing the "name" field until you find a match.
Pete