Sli*_*009 1 c# arrays dynamic-arrays
我已经制作了一个循环,每个月从当前年龄到年份x循环,比如80.
我有一个数组yearCalculation年和每年计算包含一个monthCalculation数组.(以防万一有人想对Lists发表评论,我目前正在使用数组,想看看是否有一个简单的解决方案.)
这看起来如下:
yearCalculations[] years = years.InstantiateArray(//Number of years, [80 minus age]//);
monthCalculations[] months = months.InstantiateArray(//Number of months in a year, [this should be 12]//);
Run Code Online (Sandbox Code Playgroud)
在实例化之后,我循环遍历所有时段并用各种计算填充它们.(但是,在达到年龄x之后,所有计算都将导致零):
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如你在X(80)年代可以理解的那样,计算将完成,但去年的计算将包含一些结果,而不进行计算.让我们说这是从7月开始.调整此数组大小的最简单方法是什么,删除所有月份而不进行计算(所以索引6和之后)?
仅仅为了完整性,这里是instantiateArray函数;
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;
}
Run Code Online (Sandbox Code Playgroud)
要从数组中删除空值,可以使用LINQ
var arr = years.Where(x => !string.IsNullOrEmpty(x)).ToArray();//or what ever you need
Run Code Online (Sandbox Code Playgroud)