2013-05-14 113 views
0

我一直在LINQ中拼命掙扎,我想根據日期時間字段的日期部分進行分組並聚合其他字段。LINQ Group By和聚合字段

示例表格佈局

myDateField  myIntField1 myIntField2 myIntField3 
01/02/2013  5    5    5 
01/02/2013  5    5    5 
02/02/2013  10    10    10 
02/02/2013  10    10    10 

我想與

myDateField  myIntField1 myIntField2 myIntField3 
01/02/2013  10    10    10 
02/02/2013  20    20    20 

回到我管理的列表使用MSDN的例子以下,但真的不能讓我的頭圍繞如何用它。它聲明我應該能夠訪問新的BookedList組,但不斷收到匿名類型錯誤等。

 Dim bestdays = From a In b 
         Where a.BookedOn < a.EventDayTime And a.Cancelled = False 
         Group By BookDate = a.BookedOn.Value.Date 
         Into BookedList = Group 
+1

[。取(N)](http://msdn.microsoft.com/en-us/library/bb503062.aspx)做這行你(其中n是從一個序列開始*的連續元素的數量)。或者你的問題是你所得到的錯誤? – Dave 2013-05-14 13:32:26

+0

對不起@DaveRook標題可能會誤導,我知道如何獲得5條記錄,但我的代碼似乎並沒有分組。它也不會聚合myIntFields。我知道如何在SQL中執行此操作 - 將所有myInt字段合併,然後按日期字段進行分組,如何使用LINQ-SQL完成此操作? – GJKH 2013-05-14 13:40:48

回答

1

語法Into [FIELD_NAME1] = [AGGREGATE_FUNCTION1]([VALUE1]), [FIELD_NAME2] = [AGGREGATE_FUNCTION2]([VALUE2]) ...。該鍵將自動成爲返回對象的一部分。

那麼您正在尋找這樣的事情:

Class TableRow 
    Public Property myDateField As Date 
    Public Property myIntField1 As Integer 
    Public Property myIntField2 As Integer 
    Public Property myIntField3 As Integer 
    Sub New(mydate As Date, 
      myint1 As Integer, myint2 As Integer, myint3 As Integer) 
    myDateField = mydate 
    myIntField1 = myint1 
    myIntField2 = myint2 
    myIntField3 = myint3 
    End Sub 
End Class 

Sub Main() 
    Dim tablesRows As New List(Of TableRow) 
    tablesRows.Add(New TableRow(Today, 5, 10, 15)) 
    tablesRows.Add(New TableRow(Today, 6, 11, 16)) 

    Dim v = From r In tablesRows Group By r.myDateField 
      Into Total1 = Sum(r.myIntField1), 
       Total2 = Sum(r.myIntField2), 
       Total3 = Sum(r.myIntField3) 
End Sub 
+1

完美!不僅僅是一個答案,但我認爲你已經幫我弄清楚了這個工作方式。非常感謝! – GJKH 2013-05-14 14:15:22

1

也許這SLD做你的工作

Dim bestdays = (From a In b 
       Where a.BookedOn < a.EventDayTime And a.Cancelled = False 
       Group By BookDate = a.BookedOn.Value.Date 
       Into BookedList = Group).Take(5) 
+0

感謝Manolis,請參閱上面的評論,有改變標題爲了解可能會引起誤解,我知道如何獲得5條記錄,但我的團隊是不工作的。 – GJKH 2013-05-14 13:42:37

+0

試試這個:Group通過a.BookedOn – 2013-05-14 13:47:29