c# - 调整数组大小以丢失空值

标签 c# arrays dynamic-arrays

我做了一个循环,从当前年龄到x年(例如80岁),每个月循环一次。

我有一个数组yearCalculation years并且每个yearCalculation除其他外还包含一个monthCalculation数组。 (以防万一有人想对列表发表评论,我目前正在使用数组,并想看看是否有一个简单的解决方案。)

如下所示:

yearCalculations[] years = years.InstantiateArray(//Number of years, [80 minus age]//);
monthCalculations[] months = months.InstantiateArray(//Number of months in a year, [this should be 12]//);


实例化之后,我遍历所有周期,并用各种计算填充它们。 (但是,达到年龄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
        }
    }
}


如您所知,在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;
}

最佳答案

要从数组中删除空白值,可以使用LINQ

var arr = years.Where(x => !string.IsNullOrEmpty(x)).ToArray();//or what ever you need

关于c# - 调整数组大小以丢失空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32013086/

相关文章:

php - 使用数组查询数据库

c# - New-MailContact 的等效 API

c# - 重新分配一次性对象变量如何工作?

ruby - 为什么在带有 block 的数组上调用 zip 总是返回 nil

javascript - 将 2 个相关数组映射在一起

c++ - 为什么 C++ 允许非动态分配的可变长度数组?

javascript - 在 JavaScript 中将数据构建到多维数组中

delphi - 如何使局部数组成为持久数组?

c# - 在 StreamReader 中移动指针

c# - 从类中调用连接字符串