c# - Convert SQL code to LINQ - Group By and Sum -


can not convert code linq , preview data grid view.

i have looked @ this answer not helping me

select tbl_user.id,tbl_user.name,tbl_user.family, sum(tbl_price.price)          tbl_user,tbl_price         tbl_user.id=tbl_price.user_id_fk         group tbl_user.name+''+tbl_user.family,tbl_user.id,tbl_user.name,tbl_user.family 

please me convert code linq

you need join 2 tables, group result userid , call sum method on price property value each items user.

something this

var userswithtotalprice = (from in db.users                            join b in db.userprice on a.userid equals b.userid                            select new { userid = a.userid,                                          familyname = a.name + " " + a.familyname,                                          price = b.price}                           ).groupby(f => f.userid, items => items, (a, b) => new                                      {                                           userid = a,                                           familyname = b.firstordefault().familyname ,                                           price = b.sum(g=>g.price)                                      }                           ).tolist(); 

userswithtotalprice variable collection of items each userid, familyname , price property. used anonymous projection. if have view model, can use that.

public class userwithprice {   public int id { set;get;}   public string familyname { set;get;}   public decimal price { set;get;} } 

and use in projection part

var userswithtotalprice = (from in db.users                            join b in db.userprice on a.userid equals b.userid                            select new { userid = a.userid,                                          familyname = a.name + " " + a.familyname,                                          price = b.price}                           ).groupby(f => f.userid, items => items, (a, b) =>                                     new userwithprice                                    {                                           id = a,                                           familyname = b.firstordefault().familyname ,                                           price = b.sum(g=>g.price)                                     }                           ).tolist(); 

update entity/dbset/property names based on definition.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -