0

I try to make two dimension list with dictionary.
I would like to make it, every hours, left times, right times.

1 am, ActionEnum.Left = 10, ActionEnum.Right = 20
2 am, ActionEnum.Left = 40, ActionEnum.Right = 50
3 am, ActionEnum.Left = 60, ActionEnum.Right = 70
4 am, ActionEnum.Left = 30, ActionEnum.Right = 40

...

Dictionary<ActionEnum, int> indexer1 = new Dictionary<ActionEnum, int>();
ActionEnum[] values = (ActionEnum[])Enum.GetValues(typeof(ActionEnum));
for (int i = 0; i < values.Length; i++)
{
    indexer1.Add(values[i], i);
}

Dictionary<int, Dictionary<ActionEnum, int>> indexer2 = new Dictionary<int, Dictionary<ActionEnum, int>>(); 
for (int i = 0; i < 24; i++)
{
    indexer2.Add(i, indexer1);
}


indexer2[0][ActionEnum.Left] = 10; indexer2[0][ActionEnum.Right] = 20;
indexer2[1][ActionEnum.Left] = 40; indexer2[1][ActionEnum.Right] = 50;
indexer2[2][ActionEnum.Left] = 60; indexer2[2][ActionEnum.Right] = 70;
indexer2[3][ActionEnum.Left] = 30; indexer2[3][ActionEnum.Right] = 40;

for (int i = 0; i < 24; i++)
{
    for (int j = 0; j < values.Length; j++)
    {
        Console.Write(indexer2[i][(ActionEnum)j] + " ");
    }
    Console.WriteLine();
}

It seems to work,
but when I have assigned values, the dictonary holds with last values.
Would you give me some help?

enter image description here

0

1 Answer 1

1

Because indexer1 is added to indexer2 by reference. you need to create new dictionary each time you want to add it to another dictionary. use new keyword to create new dictionary. change your second loop to this.

for (int i = 0; i < 24; i++)
{
    indexer2.Add(i, new Dictionary<ActionEnum, int>(indexer1));
}
1
  • Thanks alot. M.kazem, it work as it is. I can say more thanks.
    – tom tom
    Nov 21, 2015 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.