简体   繁体   中英

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

I'm new to C# and I'm just writing a quick/small scale app for personal use. I would like to have a Hash table that associates enum values to an array containing integers ie int [] format. Is this possible without resorting to using an ArrayList?

I played with the syntax and I am having no luck. I basically want Dictionary<Integer, int[]>

EDIT:

I'm writing a pattern matching algorithm and there are three different types represented by an enum. I am keeping track of integer values in an array of size 6 to determine a prediction.

The simplification of the problem is that there is a list of integers being built up, and it would be greatly beneficial if I could predict the next part of a sequence before it arrives.

It's a very simple algorithm, and doesn't involve anything complex other than a few math tricks like gcd, etc.

Btw, thank you for the help!

This is perfectly valid:

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

So the answer would be yes, you can do that.

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

Yes, that is possible. Example:

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];

Example for enum:

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 };

Usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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