Search code examples
vb.netlinqlinq-to-dataset

How can I put a Sum() in this linq query?


I am looking to sum the "Status" field.

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

I'm also wanting to keep this as an IEnumerable of DataRow because I will be creating a datatable from it with

Dim yyyyy As DataTable = query8.CopyToDataTable

Solution

  • Just add a call to the aggregate method you want and optionally add an alias to the result.

    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
    

    Note that there are many ways this could be written, this is just one way.