Search code examples
c#arraysdynamic-arrays

Resizing array to lose empty values


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;
}

Solution

  • 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