C# 中的多维数组
我在 C# 中定义了这个多维数组:
int[,] values = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
现在值不再是这种形式,而是在字典中:
values2.Add("KeyA", new List<float> {1,4});
values2.Add("KeyB", new List<float> {2,5});
values2.Add("KeyC", new List<float> {3,6});
现在我尝试再次解析二维数组中的这个字典,但不知何故出现了问题:
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));
}
}
这会引发 InnerException: System.IndexOutOfRangeException。但为什么?我无法正确转换这些值。
编辑:我可以假设字典中的所有值都具有相同的列表长度。我确实在其他地方检查过这个。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这就像以错误的方式获取您的长度或索引一样简单。这是您的数组创建:
然后您设置
values[i, j]
,其中i
小于metrics.Keys.Count
且 < code>j 小于list.Count
。您可以切换长度或设置
values[j, i]
。鉴于数组的原始声明,我怀疑您想要后一种方法。I think it's as simple as getting either your lengths or your indexing the wrong way round. Here's your array creation:
And you're then setting
values[i, j]
wherei
is less thanmetrics.Keys.Count
andj
is less thanlist.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.