Define a double array without a fixed size?

2019-06-17 04:42发布

问题:

Hello i have a problem with c# Arrays. I need a array to store some data in there... My Code is that

double[] ATmittelMin;
ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax);

But the compiler says: not defined var How can i define a double array without a fixed size ? Thanks a lot!

回答1:

Arrays are always fixed in size, and have to be defined like so:

double[] items1 = new double[10];

// This means array is double[3] and cannot be changed without redefining it.
double[] items2 = {1.23, 4.56, 7.89};

The List<T> class uses an array in the background and redefines it when it runs out of space:

List<double> items = new List<double>();
items.Add(1.23);
items.Add(4.56);
items.Add(7.89);

// This will give you a double[3] array with the items of the list.
double[] itemsArray = items.ToArray();

You can iterate through a List<T> just as you would an array:

foreach (double item in items)
{
    Console.WriteLine(item);
}

// Note that the property is 'Count' rather than 'Length'
for (int i = 0; i < items.Count; i++)
{
    Console.WriteLine(items[i]);
}


回答2:

From what I see you did not declare the zaehlMittel variable. I guess this is what the compiler complains about.

Apart from that, even though you can of course determine the value of that variable programmatically, the moment you want to create an array its size must be known. This is the way arrays work.

In case you cannot do that easily, I suggest using some sort of dynamic datastructure, like a list or a set. Then, once all elements have been added, you are of course still free to create an array from that, as by that time you know the number of elements (even though there are convenience methods like toArray() that will even take care of that).



回答3:

You have to instanciate the array before using it:

double[] ATmittelMin = new double[10];
ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax);


回答4:

The obvious solution that springs to mind is to use a List:

List<double> ATmittelMin = new List<double>();
ATmittelMin.Add(Gradient(x, xATMax, y, yATMax);

But if you don't want to convert from a list to an array you can grow the array later:

double[] ATmittelMin = new double[10];
// Some code
int index = some_value;
if (index >= TmittelMin.Length)
{
    Array.Resize(ATmittelMin, index+5);  // So we're not constantly resizing the array
}

It's not ideal as you're doing a lot of the work that List is doing behind the scenes - probably a lot more efficiently than you can.