简体   繁体   中英

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.

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

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

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

如果您可以使键保持唯一,那么“字典”是最佳选择,如其他答案所述,如果您希望每个值多个键,那么“查找”是最佳选择, 请参见

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