IF row value in datatable are same - sum up the amount

Hello all,

I have data sheet where if " Invoice " Column have the same values , the “amount” column should be summed up.

i.e., INV001 are repeated twice so 100 + 200
Screenshot and excel for reference.
image

Thank you all.
Book1.xlsx (8.8 KB)

@Yugal_Raju

Try the below linq

dt = dt.AsEnumerable.GroupBy("function(x) x("invoice").ToString).Select(function(g) dt.LoadDataRow(g.key.ToString,g.Sum(function(y) y("Amount").ToString).ToString).CopyToDataTable

Cheers

Can you tell me how to do it using a for each loop ? I have other criteria as well hence i’m using for each loop

' Initialize a new Dictionary
Dim invoiceSums As New Dictionary(Of String, Integer)

' Use a For Each Row activity to iterate through each row of your DataTable
For Each row As DataRow In dataTable.Rows
    ' Get the invoice number and amount from the current row
    Dim invoice As String = row("Invoice").ToString
    Dim amount As Integer = Int32.Parse(row("Amount").ToString)

    ' If the invoice number is already in the dictionary, add the current amount to the existing sum
    ' Otherwise, add a new entry to the dictionary with the current invoice number and amount
    If invoiceSums.ContainsKey(invoice) Then
        invoiceSums(invoice) += amount
    Else
        invoiceSums.Add(invoice, amount)
    End If
Next

' Now, invoiceSums contains the total amount for each unique invoice number


I reduce 1 assign instead of taking on front you should write in variable itself.
i.eDictInvoice is mention in the variable itself
here is the image shown how to do with for loop

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.