如何在这个linq查询中加上Sum()?

时间:2012-04-18 06:15:20

标签: vb.net linq linq-to-dataset

我希望总结“状态”字段。

    Dim _detailRecords As New DataTable
    _detailRecords.Columns.Add("y")
    _detailRecords.Columns.Add("z")
    _detailRecords.Columns.Add("A", GetType(Int32))

    Dim workRow As DataRow
    Dim i As Integer

    For i = 1 To 3
        workRow = _detailRecords.NewRow()
        workRow(0) = i.ToString()
        workRow(1) = "CustName" & i.ToString()
        workRow(2) = i + 1
        _detailRecords.Rows.Add(workRow)
    Next

    For i = 1 To 3
        workRow = _detailRecords.NewRow()
        workRow(0) = i.ToString()
        workRow(1) = "CustName" & i.ToString()
        workRow(2) = i + 1
        _detailRecords.Rows.Add(workRow)
    Next

Dim query8 As IEnumerable(Of DataRow) = (From record As DataRow In _detailRecords _
    Group record By y = record.Field(Of String)("y"), _
                   z = record.Field(Of String)("z"), _
                   Status = record.Field(Of Int32)("Status") Into groupedRecords = Group _
Select groupedRecords.FirstOrDefault())

我也想把它保存为DataRow的IEnumerable,因为我将用它创建一个数据表

Dim yyyyy As DataTable = query8.CopyToDataTable

1 个答案:

答案 0 :(得分:1)

只需添加对所需聚合方法的调用,并可选择为结果添加别名。

Dim query =
    From record In _detailRecords
    Group record
        By Y = record.Field(Of String)("y"),
           Z = record.Field(Of String)("z"),
           Status = record.Field(Of Int32)("Status")
        Into groupedRecords = Group,
             Sum(record.Field(Of Int32)("Status")) ' Get the sum of the Status values
    Select FirstRecord = groupedRecords.FirstOrDefault,
           Sum

请注意,有很多方法可以编写,这只是一种方式。