简体   繁体   中英

Apply “new” to only one dimension of multi-dimensional array?

I have this C# program, and it has the following code:

/*10 data for one peprson */
private int[] data = new int[10];
private void SomeMethod()
{   
    /*More code*/
    this.data = new int[10];
    /*More code*/
}

This program calls this method when an event occurs, and every time that happens, this one-dimensional array gets a "new" instance of an array of size 10, and refresh the array. Kinda like resetting it.

Now, I was told to write a new program that does the same thing, except that there are 5 people now. So I created a 2-dimensional array like

private int[,] data = new int[5, 10];

which will be able to store 10 data for each of the 5 people. Now I am at a loss on how to refresh/reset only one person's data from this 2-d array. I tried

private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
     this.data[index] = new int[10];
}

but this clearly does not work, and I get an error saying I am missing a dimension. Is there a way to achieve this? For the time being, I am using

private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
     for(int i=0; i<10; i++)
         this.data[index, i] = 0;
}

When I tested it with the original code, I noticed that every time it got a "new" instance, it was assigning 0's to the array. Now the difference is that the original one is referencing the new instance with no data (and hence 0?), and the rewritten one is overwriting with 0's.

Do these two basically work the same way, program's-function-wise?

There's nothing wrong with the code you have. It's even likely faster than creating the new array. But if you really want to, you can use a jagged array instead:

private int[][] data = new int[5][];

//...

private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
     this.data[index] = new int[10];
}

But arrays seem weird for this. A List<T> might be better:

private List<int[]> data = new List<int[]>();

where you can then use the .Add() method as you get new records, and use the Count property to know how many you've added.

Moreover, it's common to find out the int[10] array was actually a stand-in for named fields, where each position in the array has meaning. In that situation, you're usually much better off building a class for this data, where each item in the array is a named field in the class (we'll just call it MyClass for now). Then you end up with something like this:

private List<MyClass> data = new List<MyClass>();

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