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 ?

Gustav Bertram
  • 14,591
  • 3
  • 40
  • 65

1 Answers1

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();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • The error is caused becuse a lambda expression returns a single expression (`row.Field("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. – Zev Spitz Dec 20 '13 at 08:26