LukAss741
LukAss741

Reputation: 831

2 dimensional array in C# like in other languages

I have data like this:

44 {5,8,0,0,2,5,9}
99 {9,9,9,9,5,5,1}
12 {0,0,9,5,1,7,1}

The first number is like a primary key and other numbers in brackets are its values.

I would like to save the data above into arrays like this:

int id = 0;
int ids[];
int data[][7];

ids[id] = 44;
data[ids[id]][0] = 5;
data[ids[id]][1] = 8;
data[ids[id]][2] = 0;
data[ids[id]][3] = 0;
data[ids[id]][4] = 2;
data[ids[id]][5] = 5;
data[ids[id]][6] = 9;
id++;
ids[id] = 99;
data[ids[id]][0] = 9;
data[ids[id]][1] = 9;
data[ids[id]][2] = 9;
data[ids[id]][3] = 9;
data[ids[id]][4] = 5;
data[ids[id]][5] = 5;
data[ids[id]][6] = 1;
id++;
ids[id] = 12;
data[ids[id]][0] = 0;
data[ids[id]][1] = 0;
data[ids[id]][2] = 9;
data[ids[id]][3] = 5;
data[ids[id]][4] = 1;
data[ids[id]][5] = 7;
data[ids[id]][6] = 1;
id++;

And then acces them like this:

Console.Write(""+data[44][0]);
output: 5

I hope you get what I mean. This is a very basic example of using arrays that I can't find how to use in C#. How could I do this? I have read Arrays Tutorial on msdn but I coldn't have even found how to create an array with first dimension dynamic (from 0 to infinite) and second static (from 0 to 6). Is there any simple solution how to do it? Thanks.

Upvotes: 1

Views: 178

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

In .NET you use a Dictionary<TKey, TValue> if the key is unique what "The first number is like a primary key" suggests. You can use an int[] or List<int>(if it should be mutable) as value.

var dict = new Dictionary<int, int[]>();
var values = new[] { 5, 8, 0, 0, 2, 5, 9 };
dict.Add(44, values);
values = new[] { 9, 9, 9, 9, 5, 5, 1 };
dict.Add(99, values);
// ...

You access it via key in a very efficient way:

Console.Write(dict[44][0]);  // 5

Upvotes: 2

Pankaj
Pankaj

Reputation: 2744

If you can keep your key as unique, then Dictionary is the best option for this as mentioned in the other answers, , if you want multiple keys per value then Lookup is the best option, See this

Upvotes: 0

doogle
doogle

Reputation: 3406

You could use a Dictionary<int, List<int>>:

var data = new Dictionary<int, List<int>>();
data.Add(44, new List<int> { 5, 8, 0, 0, 2, 5, 9 });
data.Add(99, new List<int> { 9, 9, 9, 9, 5, 5, 1 });
//....

and to utilize:

var id = 44;
var value1 = data[id][0];
// ...

Upvotes: 1

TGH
TGH

Reputation: 39248

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


data.Add(44, new int[]{5,8,0,0,2,5,9});
data.Add(99, new int[]{9,9,9,9,5,5,1});
data.Add(12, new int[]{0,0,9,5,1,7,1});

By using a dictionary you can get the desired effect with less complexity. It will enable you to create a unique key per array

Upvotes: 2

Related Questions