Thursday, February 23, 2006

Multiple keys with KeyedCollection

I'm currently dealing with some objects that have two different unique identifiers. One is a public, user-friendly identifier, and the other is an internal, essentially meaningless one. Meaningless, that is, other than the fact that I can ensure that it stays the same for all time, as opposed to the one that users can see, which therefore will no doubt need to be altered 30 times as random punter X changes their mind yet again.

As a result I wanted a collection where it's possible to grab an item quickly and easily using either of the identifiers. Deriving from KeyedCollection<TKey, TItem> does the job nicely for a single key, so I thought I'd extend that a bit farther and come up with my own cunningly named DoubleKeyedCollection<TKey, TSecondKey, TItem>.

To my shame, I've not even tested this code before posting it up here as it's already long past the end of the day, although it does compile, which is always encouraging if nothing else. I'm not hugely fond of the choice of GetItem() as a method name as it's a bit ambiguous, especially if your two keys are of the same type. GetItemBySecondKey() seemed a bit meaningless to an end client using a class derived from DoubleKeyedCollection though. Any thoughts on the subject are welcome (as is notification of any blatant errors that I've managed to completely overlook).

As an aside, I think I'll be examining the possibilities of changing the layout of this page. The narrow column doesn't exactly lend itself to code listings. I've done what I can to make it readable. EDIT: Template now changed - not as pretty imho, but makes the code a lot easier to read!

No comments: