Groupby Linq Updated Version

Hi Team,

I am using a Groupby for multiple columns.

(From d In ExtractedTableDt.AsEnumerable()
Group d By k1 = d(4).ToString().Trim(), k2 = d(9).ToString().Trim()
Into grp = Group
Let s11 = String.Join(“,”, grp.Where(Function(x) Not String.IsNullOrEmpty(x(0).ToString().Trim)).Select(Function(x) x(1).ToString()))
Let s12 = String.Join(“,”, grp.Where(Function(x) Not String.IsNullOrEmpty(x(2).ToString().Trim)).Select(Function(x) x(2).ToString()))
Let s13 = grp.Sum(Function(x) CDbl(x(1).ToString.Trim))
Let s14 = grp.Sum(Function(x) CDbl(x(3).ToString.Trim))
Let ra = New Object() {s11, k1, s13, s14, s12, k2}
Select Dt_ProfitCenter.Rows.Add(ra)).CopyToDataTable()

But the issue i am facing in this is that, my d(9) can be empty for some rows.
What should i use in that case?
For blank d(9), the value of k2 will be also blank.

Any help?

Hi @yash.choursia

Try this syntax:

(From d In ExtractedTableDt.AsEnumerable()
Group d By k1 = d(4).ToString().Trim(), k2 = If(String.IsNullOrEmpty(d(9).ToString().Trim()), "", d(9).ToString().Trim())
Into grp = Group
Let s11 = String.Join(",", grp.Where(Function(x) Not String.IsNullOrEmpty(x(0).ToString().Trim())).Select(Function(x) x(1).ToString()))
Let s12 = String.Join(",", grp.Where(Function(x) Not String.IsNullOrEmpty(x(2).ToString().Trim())).Select(Function(x) x(2).ToString()))
Let s13 = grp.Sum(Function(x) If(String.IsNullOrEmpty(x(1).ToString().Trim()), 0.0, CDbl(x(1).ToString().Trim())))
Let s14 = grp.Sum(Function(x) If(String.IsNullOrEmpty(x(3).ToString().Trim()), 0.0, CDbl(x(3).ToString().Trim())))
Let ra = New Object() {s11, k1, s13, s14, s12, k2}
Select Dt_ProfitCenter.Rows.Add(ra)).CopyToDataTable()

Hope it helps!!

1 Like

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