Linq query to sum the 5 column values and save in new column

As in the below attached snip i want to perform the sum of column A, B, C, and D and save the result in Final, Kindly help with a linq query to perform this
image

Hi @Amrutha.mg

Try this
=> Read Range Workbook
image
Output-> dt

=> Use below syntax in Assign:

Assign-> dt= (From row In dt.AsEnumerable()
                     Let sum = row.Field(Of Double)(0) + row.Field(Of Double)(1) + row.Field(Of Double)(2) + row.Field(Of Double)(3)
                     Select newRow = dt.Clone().LoadDataRow({row(0), row(1), row(2), row(3), sum}, False)).CopyToDataTable()

=> Write Range Workbook dt to same sheet
image

Sequence.xaml (7.8 KB)

Regards

Hi,

Another approach: can you try the following sample?

dt.AsEnumerable.Select(Function(r) dt.CLone.LoadDataRow( r.ItemArray.SkipLast(1).Concat({r.ItemArray.SkipLast(1).Sum(Function(o) CDbl(o.ToString))}).ToArray(),False)).CopyToDataTable()

Sample
Sample20240226-2 (2).zip (10.1 KB)

Or we can also achieve it using DataColumn.Expression as the following

dt.Columns(4).Expression = "[A]+[B]+[C]+[D]"

image

Regards,

1 Like

Hi @Amrutha.mg

Another approach using invoke code.

For Each row In dt.AsEnumerable
row(4)=row.ItemArray.SkipLast(1).Sum(function(a) cint(a.ToString))
Next

Cheers!!

hey @Amrutha.mg
Here is simple vb.net code:

For Each row As DataRow In dt.Rows
    Dim sum As Decimal = 0
    For i As Integer = 0 To 3 
        If Not IsDBNull(row(i)) Then sum += Convert.ToDecimal(row(i))
    Next

    row(4) = sum
Next

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