If I want to use objects as the keys for a Dictionary, what methods will I need to override to make them compare in a specific way?
Say I have a a class which has properties:
class Foo { public string Name { get; set; } public int FooID { get; set; } // elided }
And I want to create a:
Dictionary<Foo, List<Stuff>>
I want Foo objects with the same FooID to be considered the same group. Which methods will I need to override in the Foo class?
To summarize: I want to categorize Stuff objects into lists, grouped by Foo objects. Stuff objects will have a FooID to link them to their category.
By default, the two important methods are
GetHashCode()andEquals(). It is important that if two things are equal (Equals()returns true), that they have the same hash-code. For example, you might ‘return FooID;’ as theGetHashCode()if you want that as the match. You can also implementIEquatable<Foo>, but that is optional:Finally, another alternative is to provide an
IEqualityComparer<T>to do the same.