-5

I want to remove GROUP BY clause from the below code. How could i do this.

var newDt = dt.AsEnumerable()
              .GroupBy(r => r.Field<string>("BATCH NUM"))
              .Select(g =>
              {
                  var row = dt.NewRow();

                  row["BATCH NUM"] = g.Key;
                  row["QTY"] = g.Sum(r => Convert.ToInt32(r.Field<string>("QTY")) + Convert.ToInt32(r.Field<string>("BONUS")));
                  row["PROD ID"] = String.Join(",", g.Select(x => x.Field<string>("PROD ID")).Distinct());
                  // row["PROD ID"] = g.Select(r => r.Field<string>("PROD ID"));
                  return row;
              }).CopyToDataTable();

It creates problem, when we have two Different "PROD ID" but with same "BATCH NUM"then it combines "PROD ID" into a single field it treats both PROD ID with same batch. Here is a Image you can see

Result which i want is like below.

1 Answers1

1

If you try to delete the Group By it give you an error becouse you do a Sum in the select. The object that you "GROUP" is not longer a Set of TKey, TElement when you delete it.

If you want to do a Sum of "QTY" of each "PROD ID" and collect the "BATCH NUM", that is the best way.

There is another way using a ToLookup but: lookup vs. groupby

Details asked in comments:

With the lookup you can do the same thing...

var newDt = dt.AsEnumerable()
.ToLookup(r => r.Field<string>("PROD ID"))
.Select(g =>
{
     var row = dt.NewRow();
     row["PROD ID"] = g.Key;
     row["QTY"] = g.Sum(r => Convert.ToInt32(r.Field<string>("QTY")) + Convert.ToInt32(r.Field<string>("BONUS")));
     row["BATCH NUM"] = String.Join(",", g.Select(x => x.Field<string>("BATCH NUM")));
     return row;
}).CopyToDataTable();

Is quite the same thing, the difference is in the post that i linked below.

Hamlet Leon
  • 427
  • 3
  • 9