繁体   English   中英

如何将整数数组存储到C#中的字典中? 即是 <Integer, int[]> 可能?

[英]How or is it possible to store an array of integers into a dictionary in C#? i.e. is <Integer, int[]> possible?

我是C#的新手,我只是在写一个供个人使用的快速/小型应用程序。 我想有一个哈希表,将枚举值关联到包含整数(即int []格式)的数组。 是否可以不借助ArrayList而实现?

我玩过语法,但没有运气。 我基本上想要Dictionary<Integer, int[]>

编辑:

我正在写一个模式匹配算法,枚举代表三种不同的类型。 我跟踪大小为6的数组中的整数值以确定预测。

问题的简化是正在建立一个整数列表,如果我可以在序列的下一部分到达之前对其进行预测,那将是非常有益的。

这是一种非常简单的算法,除了gcd等一些数学技巧外,不涉及任何复杂的事情。

顺便说一句,谢谢您的帮助!

这是完全正确的:

var dict = new Dictionary<int, int[]>();
dict.Add(1, new int[] {1, 2, 3});

因此,答案是肯定的,您可以做到。

您可以使用Dictionary<int, int[]>Dictionary<int, List<int>>

是的,那是可能的。 例:

Dictionary<int, int[]> items = new Dictionary<int, int[]>();

// add an item using a literal array:
items.Add(42, new int[]{ 1, 2, 3 });

// create an array and add:
int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;
items.Add(4, values);

// get one item:
int[] values = items[42];

枚举示例:

enum MyEnum
{
    Value1,
    Value2,
    Value3
}

...

var dictionary = new Dictionary<MyEnum, int[]>();

dictionary[MyEnum.Value1] = new int[] { 1, 2, 3 };
dictionary[MyEnum.Value3] = new int[] { 4, 5, 6 };
dictionary[MyEnum.Value3] = new int[] { 7, 8, 9 };

用法:

int i = dictionary[MyEnum.Value1][1]; // i == 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM