I'm not 100% sure of the exact data you want to use as a key. I think 2? 2 Integer values? That's what I'll assume below, but if you want three or the type is different, just adjust accordingly. I suggest the following (step 1 is necessary, step 2 is optional but I'd do it)
Step 1 Creating your own key struct, to be used as the key in a standard dictionary. Give it 2 properties (or three, whatever) for your values that will act as the key, and/or a Constructor taking/setting those values.
Specify a GetHashCode method. Something like:
public override int GetHashCode()
{
unchecked
{
return (_empId * 397) ^ _payYr;
}
}
Note: Yes, you could use a Tuple. Tuples . . . aren't as cool as the first seem. Your property names will be Item1, etc. Not very clear. And you often end up wanted to overriding and add things soon enough. Just start from scratch.
Like this:
public struct PayKey {
private int _empId
private int _payYr;
public PayKey (int empId, int payYr) {
_empId = empId;
_payYr = payYr;
}
public override int GetHashCode()
{
{
return (_empId * 83) ^ _payYr;
}
}
}
Note: If any of your multiple values that you want to use in your combined key are reference types, you should probably create a class instead of a struct. If so, you'll also need to override Equals
for it to work properly as a dictionary key.
public override bool Equals( object pkMaybe ){
if( pkMaybe is PayKey ) {
PayKey pk = (PayKey) pkMaybe ;
return _empId = pk.EmpId && _payYr = pk.PayYr;
}
else {
return false;
}
}
(And add public properties for your key values if you haven't already.)
Or, if you create the custom dictionary as I mention below, it would be convenient use a IEqualityComparer. (Basically, if you use a class as your key, you have to make sure the dictionary will see two identical PayKey object as "equal". By default, even with equal values, they are references to different objects, so the framework will consider them not equal)
Step 2 Create a class that inherits from Dictionary. Give it two additional methods:
- An add method that takes your two key parameters as well as the value you want to add. Inside, you'll construct one of your key structs and call its base add method, with the key object as the key and your value of course as the value.
- an overload for item or named as you wish. This method will take as parameters the 2 integers of your key, and return the item. Inside this method you'll construct one of your key structs, and call the base item method with the key struct to retrieve the object.
- Additionally, for your eventual convenience, you'll probably want to add other overloads to your dictionary, where you can specify your key values, rather than having to construct your own key struct each time. For example, the first thing I'd probably do is add a KeyExists property that took my two key values.