我想计算一个值(双精度)数组中元素的平均值或总和或其他方法,条件是具有相同长度的第二个数组。
例如,我有一个带有日期 (double[]dts) 的排序数组,现在我想计算值数组 (double[]vals) 上的开始日期 (std) 和结束日期 (edd) 之间的平均值(即简单,我下面的代码做了什么)。
但是,如果我想计算一年中所有星期一的平均值,下面的代码将不再起作用。有任何想法吗?谢谢!
public static double aggr(double[] dts, double[] vals, double std, double edd)
{
int stdindex = 0;
int eddindex = dts.Length;
for (int k = 0; k < dts.Length; k++)
{
if (dts[k] == std)
{
stdindex = k;
}
if (dts[k] == edd)
{
eddindex = k;
}
}
return vals.Skip(stdindex).Take(eddindex-stdindex).Average();
}
谢谢大家。我认为所有答案都有效。这是我的新代码:
public static double aggr(double[] dts, double[] vals, double std, double edd, string peakoffpeakbase, double sumavg)
{
double result;
if (sumavg == 1)
{
if (peakoffpeakbase=="Peak")
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std & dv.d < edd & DateTime.FromOADate(dv.d).DayOfWeek != DayOfWeek.Saturday & DateTime.FromOADate(dv.d).DayOfWeek != DayOfWeek.Sunday & DateTime.FromOADate(dv.d).Hour > 7 & DateTime.FromOADate(dv.d).Hour < 20))
.Select(dv => dv.v).Sum();
}
else if (peakoffpeakbase=="Offpeak")
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std & dv.d < edd & DateTime.FromOADate(dv.d).DayOfWeek == DayOfWeek.Saturday | DateTime.FromOADate(dv.d).DayOfWeek == DayOfWeek.Sunday | DateTime.FromOADate(dv.d).Hour < 8 | DateTime.FromOADate(dv.d).Hour > 19))
.Select(dv => dv.v).Sum();
}
else
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std && dv.d < edd))
.Select(dv => dv.v).Sum();
}
}
else
{
if (peakoffpeakbase == "Peak")
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std & dv.d < edd & DateTime.FromOADate(dv.d).DayOfWeek != DayOfWeek.Saturday & DateTime.FromOADate(dv.d).DayOfWeek != DayOfWeek.Sunday & DateTime.FromOADate(dv.d).Hour > 7 & DateTime.FromOADate(dv.d).Hour < 20))
.Select(dv => dv.v).Average();
}
else if (peakoffpeakbase == "Offpeak")
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std & dv.d < edd & (DateTime.FromOADate(dv.d).DayOfWeek == DayOfWeek.Saturday | DateTime.FromOADate(dv.d).DayOfWeek == DayOfWeek.Sunday | DateTime.FromOADate(dv.d).Hour < 8 | DateTime.FromOADate(dv.d).Hour > 19)))
.Select(dv => dv.v).Average();
}
else
{
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d >= std && dv.d < edd))
.Select(dv => dv.v).Average();
}
}
return result;
}
显然这很糟糕而且非常冗长。我真正想做的是结合下面的答案并写下:
result = dts.Zip(vals, (d, v) => new { d, v })
.Where(dv => (dv.d.InTimeRange(std,edd).IsBusinessHour(peakoffpeakbase))
.Select(dv => dv.v).CustomX(indicator);
其中 InTimeRange 和 IsBusinessHour 是如下所述的扩展方法,customX 将接受一个参数,然后进行平均、求和或其他操作。但是我不能让它工作。再次感谢!