gg17
gg17

Reputation: 139

Grouping by multiple fields in linq to sql

I'm having a problem of defining a data type for a list of grouped rows in LINQ to SQL.
I have a model MyDBModel with 2 properties

public class MyDBModel
{
  public List<a_Cases_tbl> a_Cases { get; set; }
  public List<b_Cases_tbl> b_Cases { get; set; }
}

In a controller I try to get data into this properties

MyDBDataContext myDb = new MyDBDataContext();
var listModel = new MyDBModel();
listModel.a_Cases= 
   (from t in myDb.a_cases_table
    group t by new { t.Date, t.Name, t.Category, t.Code }
    into myGroup
    select new { myGroup.Key.Date, myGroup.Key.Name, myGroup.Key.Category, myGroup.Key.Code  });
listModel.b_Cases = 
 (from t in myDb.B_cases_table
  group t by new { t.Date, t.Name, t.Category, t.Code }
  into myGroup
  select new { myGroup.Key.Date, myGroup.Key.Name, myGroup.Key.Category, myGroup.Key.Code  });

I get error:

Cannot implicitly convert type 'System.Collections.Generic.List < AnonymousType#1 > ' to 'System.Collections.Generic.List < MVC4.a_Cases_tbl > '

What will Data type for a_Cases should be if the result is going to be a List of Grouped by Multiple columns? Or how to define List < IGrouping < Tkey, Telement > > if the result is grouped by multiple fields of different types?

Upvotes: 0

Views: 210

Answers (1)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

In your code you have created the list of anonymous type. You must tell compiler that you create the objects of appropriate type.

select new  a_Cases_tbl{ myGroup.Key.Date, myGroup.Key.Name, myGroup.Key.Category, myGroup.Key.Code  });

....

select new b_Cases_tbl{ myGroup.Key.Date, myGroup.Key.Name, myGroup.Key.Category, myGroup.Key.Code  });

Upvotes: 1

Related Questions