3

I defined this multi dimensional array in C#:

int[,] values = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; 

Now the values are not longer in this form but in a Dictionary:

values2.Add("KeyA", new List<float> {1,4}); values2.Add("KeyB", new List<float> {2,5}); values2.Add("KeyC", new List<float> {3,6}); 

Now I'm trying to parse this dictionary in the two dimensional array again, but somehow there are problems:

List<float> outList = new List<float>(); values2.TryGetValue(values2.Keys.ElementAt(0) as string, out outList); int[,] values = new int[outList.Count, values2.Keys.Count]; for (int i = 0; i < values2.Keys.Count; i++) { List<float> list = new List<float>(); values2.TryGetValue(values2.Keys.ElementAt(i), out list); for (int j = 0; j < list.Count; j++) { values[i, j] = Convert.ToInt32(list.ElementAt(j)); } } 

This throws an InnerException: System.IndexOutOfRangeException. But why? I'm not able to convert the values properly.

Edit: I can be assumed that all the values in the dictionary have the same list length. I do check this somewhere else.

3
  • System.IndexOutOfRangeException which line? Commented Nov 16, 2010 at 9:41
  • What is metrics.Keys.Count ? and in the declaration of int [,] values you are using the same variable in values.Keys.Count. That does not even compile? Commented Nov 16, 2010 at 9:42
  • values[i, j] = Convert.ToInt32(list.ElementAt(j)); Commented Nov 16, 2010 at 9:43

1 Answer 1

5

I think it's as simple as getting either your lengths or your indexing the wrong way round. Here's your array creation:

int[,] values = new int[outList.Count, values.Keys.Count]; 

And you're then setting values[i, j] where i is less than metrics.Keys.Count and j is less than list.Count.

You could either switch the lengths round or set values[j, i] instead. Given the original statement of the array, I suspect you want the latter approach.

Sign up to request clarification or add additional context in comments.

2 Comments

@ Jon Skeet: Is there any LINQ method to do this?
@Pramodh: not that I'm aware of.