在下面的linq查询中,我有一个除零异常,我似乎无法编码。当fldDevider的Sum返回0时发生。
Dim lstToReturn As List(Of MonthData)
lstToReturn = (
From myRow In dtSpotData.AsEnumerable()
Group myRow By myRow.Field(Of DateTime)(fldstartdate).Month Into Group
Select New MonthData() With {
.Month = Month,
.ValuePerMonth =
(
Group.Sum(Function(dr) dr.Field(Of [Decimal])(fldSomeGeneralValue)) /
(
Group.Sum(Function(dr) CDec(dr.Field(Of String)(fldDevider)))
)
)
}
).ToList()
如何确保ValuePerMonth字段为0时,Group.Sum(Function(dr) CDec(dr。Field(Of String)(fldDevider))函数返回0。或者,如果Sum fldDevider实际上是0,我如何返回1 ?
也欢迎提供一些关于如何更好地从字符串转换为十进制的技巧。
我习惯c#语法,但我会使用'let'来捕获除法数的值,并且仅在它大于零时使用它,否则使用1。
Dim lstToReturn As List(Of MonthData)
lstToReturn = (
From myRow In dtSpotData.AsEnumerable()
Group myRow By myRow.Field(Of DateTime)(fldstartdate).Month Into Group
Let div = Group.Sum(Function(dr) CDec(dr.Field(Of String)(fldDevider)))
Select New MonthData() With {
.Month = Month,
.ValuePerMonth =
(
Group.Sum(Function(dr) dr.Field(Of [Decimal])(fldSomeGeneralValue)) / If(div > 0, div, 1)
)
}
).ToList()