How to use a compound key for a dictionary?

I need to arrange the sorting of the dictionary, where the key will be a pair of enum and int and value is an object. So I want to map a pair to some object.

One of the options:

public enum SomeEnum { value1, value2 } class Key { public SomeEnum; public int counter; // Do I have to implement Compare here? } Dictionary<SomeEnum, object> _myDictionary; 

Another option converts enum and int into some unique key.

 string key = String.Format("{0}/{1}", enumValue, intValue) 

This approach requires string parsing, a lot of extra work.

How to make it easy?

+6
dictionary generics c #
source share
3 answers

I would go with something like

 public enum SomeEnum { value1, value2 } public struct Key { public SomeEnum; public int counter; } Dictionary<Key, object> 

I think it will do?

+9
source share

If you are going to put this in a dictionary, you need to make sure that you implement the meaningful .Equals and .GetHashCode , or the dictionary will behave correctly.

I would start with something like the following for the main composite key, and then implement a custom IComparer to get the desired sort order.

 public class MyKey { private readonly SomeEnum enumeration; private readonly int number; public MyKey(SomeEnum enumeration, int number) { this.enumeration = enumeration; this.number = number; } public int Number { get { return number; } } public SomeEnum Enumeration { get { return enumeration; } } public override int GetHashCode() { int hash = 23 * 37 + this.enumeration.GetHashCode(); hash = hash * 37 + this.number.GetHashCode(); return hash; } public override bool Equals(object obj) { var supplied = obj as MyKey; if (supplied == null) { return false; } if (supplied.enumeration != this.enumeration) { return false; } if (supplied.number != this.number) { return false; } return true; } } 
+8
source share

If you are using C # 4.0, you can use the Tuple class.

 var key = Tuple.Create(SomeEnum.Value1, 3); 
+7
source share

All Articles