Search code examples
c#dictionaryvaluetuple

How to create a dictionary with a 3-dimensional key


I need some kind of structure that works like a dictionary, but the key is a 3D point (represented by 3 integers).

Ball b1 = new Ball();
Ball b2 = new Ball();

D[-1,3,29] = b1;
D[9,0,3] = b2;

I'm thinking about creating something like this:

Dictionary<int, Dictionary<int, Dictionary<int, Ball>>> D = new ...

Is there a better approach?


Solution

  • A ValueTuple has the appropriate equality and hashcode behavior when used with simple types. As such you can use them (and are suitable) in a dictionary.

    var dict = new Dictionary<(int,int,int),something>
    dict.Add((1,2,3), sometthing);