C# 中的多维数组

发布于 2024-10-02 20:52:38 字数 967 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∝单色的世界 2024-10-09 20:52:38

我认为这就像以错误的方式获取您的长度或索引一样简单。这是您的数组创建:

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

然后您设置 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文