Linq Query on Group By and Sum

I have a datatable as below. I want to group by using Col3 and take sum of Col2 in Col5

Input Datatable:

Col1 – Col2 – Col3 – Col4
A – 11 – AA – XYZ
B – 12 – RT – XYZ
C – 13 – HL – XYZ
D – 27 – AA – XYZ
E – 17 – AA – XYZ
F – 15 – RT – XYZ
G – 24 – HL – XYZ

OutPut required:

Col1 – Col2 – Col3 – Col4 - Col5
A – 11 – AA – XYZ - 55
D – 27 – AA – XYZ -
E – 17 – AA – XYZ -
B – 12 – RT – XYZ - 27
F – 15 – RT – XYZ -
C – 13 – HL – XYZ - 37
G – 24 – HL – XYZ -

Please help me with the LINQ query.

@vvaidya @ClaytonM Could you please help here

@tmond
Welcome to the forum

We can do it with folloing flow:
grafik

(From d In dtData.AsEnumerable
Group d By k=d("Col3").toString.Trim Into grp=Group
Let gs = grp.Sum(Function (x) CInt(x("Col2").toString))
Let raa = grp.Select(Function (g,i) If(i=0,g.ItemArray.Append(gs).toArray,g.ItemArray.Append(Nothing).toArray)).toarray
From m In raa
Select dtResult.Rows.Add(m)).CopyToDataTable

And will get:
grafik

Find starter help here:
GroupBy_1Col_AddSumToFirstMember.xaml (9.0 KB)

Also have a look here:

3 Likes

Thanks a lot @ppr, it worked!!

1 Like

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