7

I am using Linq to group by some columns in my datatable

List<DataTable> tables = ds
  .Tables[0]
  .AsEnumerable()
  .GroupBy(row => row.Field<string>("EMAIL"), row.Field<string>("NAME"))
  .Select(g => g.CopyToDataTable())
  .ToList();

I am getting an build error "The name 'row' does not exists in the current context" ? How to handle multiple group by ?

0

1 Answer 1

11

Use anonymous object for that:

List<DataTable> tables = ds.Tables[0].AsEnumerable()
                           .GroupBy(row => new {
                               Email = row.Field<string>("EMAIL"), 
                               Name = row.Field<string>("NAME") 
                           }).Select(g => g.CopyToDataTable()).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

The error is caused becuse a lambda expression returns a single expression (row.Field<string>("EMAIL")) and the compiler is interperting the expression after the comma as another parameter to the GroupBy method. Since that is outside the context of the expression, where there is no row variable, the compiler gives this error. This answer resolves the problem by having the lambda expression return a single expression - one anonymous object.