2011-04-27 96 views
1

在下面的linq查詢中,除了零外,我似乎無法編碼。我怎樣才能確保ValuePerMonth字段爲0它發生在fldDevider的總和返回0如何在Linq中處理零除以

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() 

當Group.Sum(功能(DR)CDEC(dr.Field(串)(fldDevider)) )函數返回0,或者如果實際爲0,我如何返回Sum 1 fldDevider的1。

有關如何更好地從字符串轉換爲小數的提示也值得歡迎。

回答

3

我用C#語法,但我會用一個「讓」捕捉分割數的值,而只使用它,如果它是大於零,否則使用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() 
+0

謝謝很多,在Linq文檔和示例中,這確實是一個很難找到的問題。 – CodingBarfield 2011-04-27 09:12:24