- Home /
How to make a certain kind 2D Dictionary?
What I want to know is how to make a Dictionary in which its key is a 2D array/List but the value is only a single value. It must be a dictionary because both dimensions of the key are enums. For example, if these were the enums:
enum bar {first, second, third};
enum foo {a, b, c};
The dictionary would be like, for example: Where the "bar" enums represent the 2D array key, and the "foo" enums represent the value of each combination of the 2D key.
All I want to know is how to do this, or at least how to go about doing it.
Answer by gorsefan · Jun 19, 2016 at 10:18 PM
Enums are stored internally as ints, and you can easily cast back and forth. So you can do;
int enumAsInt = (int) bar.first;
bar intAsEnum = (bar) enumAsInt;
Knowing this, you can use an 3d array instead of a Dict
int[,] lookup = new int [Enum.GetNames(typeof(FirstEnum)).Length] [Enum.GetNames(typeof(SecondEnum)).Length];
// loop over enum values
foreach (FirstEnum outer in System.Enum.GetValues (typeof(FirstEnum)))
{
foreach (SecondEnum inner in System.Enum.GetValues (typeof(SecondEnum)))
{
lookup [(int)outer] [(int)inner] = (int) ThirdEnum.data;
...
That's fiddly, and completely untested but the idea would work.
If you really want a Dict, you want to make a "composite key". I would make a series of structs based on the two enum values that represent the key, and use those structs as the Dict keys. If you want to know how that works "under the hood", read up on Object.GetHashCode
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Enum for Animation Issue 1 Answer
Accessing a Class's Variables from within a Dictionary Element 1 Answer
Enum has "Unknown resolve error" 1 Answer