Reputation: 1508
I have made a loop that loops for every month from a current age through year x, say 80.
I have an array yearCalculation years and every yearCalculation contains among other things an array of monthCalculation. (Just in case anyone wants to throw a comment about Lists, I am currently using arrays and want to see if there is an easy solution.)
This looks as following:
yearCalculations[] years = years.InstantiateArray(//Number of years, [80 minus age]//);
monthCalculations[] months = months.InstantiateArray(//Number of months in a year, [this should be 12]//);
After the instantiation I loop through all the periods and fill them with all sorts of calculations. (However, after age x is being reached, all calculations will result in zero):
for (int i = 0; i < yearCalculations.Length; i++) {
for (int j = 0; j < yearCalculations[i].monthCalculations.Length; j++) {
Double age = calculateAge(birthDate, dateAtTimeX);
if(age < ageX){
//Do all sorts of calculations.
}else{
//Break out of the loops
}
}
}
As you can understand at age X (80), the calculations will be complete, but the last yearcalculation will contain some results, without calculations being made. Lets say this is from month 7 and on. What is the easiest way to resize this array, removing all the months without calculations (So index 6 and on)?
Just for the sake of completeness, here is the instantiateArray function;
public static T[] InstantiateArray<T>(this T[] t, Int64 periods) where T : new()
{
t = new T[periods];
for (int i = 0; i < t.Length; i++){
t[i] = new T();
}
return t;
}
Upvotes: 1
Views: 1426
Reputation: 186
You can't resize an array.
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
What methods like Array.Resize actually do is allocate a new array and copy the elements over. It's important to understand that. You're not resizing the array, but reallocating it.
So long as you're using arrays, in the end the answer is going to boil down to "allocate a new array, then copy what you want to keep over to it".
Upvotes: 2
Reputation: 1881
To remove blank values from the array you could use LINQ
var arr = years.Where(x => !string.IsNullOrEmpty(x)).ToArray();//or what ever you need
Upvotes: 8
Reputation: 1706
The Array.Resize method should do the trick with the new total length. You know the total new length to be the total old length - (12 - month as an int in year)
Upvotes: 1