group by in lambda expression mvc with c# -
i have lambda expression returning correct values want sum of grouped items well, here query
ienumerable<cjtviewmodel> objmodel = (from q in db.current_jct_transaction q.job == job group q new { q.cost_code, q.category } g select new cjtviewmodel() { job = job, category_e = g.key.category == "e" ? g.sum(s => s.amount) : 0, category_l = g.key.category == "l" ? g.sum(s => s.amount) : 0, category_lb = g.key.category == "lb" ? g.sum(s => s.amount) : 0, category_oh = g.key.category == "oh" ? g.sum(s => s.amount) : 0, cost_code = g.key.cost_code, category = g.key.category }).tolist().orderby(x => x.cost_code );   it gives me output below
cost code category amount ------------------------------------------------ 1001 e $100 1001 l $200 1001 oh $120 1002 l $100 1002 lb $100 1002 oh $200
but wants output below
cost code category amount ---------------------------------------------- 1001 e $100 1001 l $200 1001 oh $120 ----------------- $420 1002 l $100 1002 lb $100 1002 oh $200 ----------------- $400
any appreciated..
you should use model holds total , details each category of given cost code. should group transactions cost code , select these models. inside each cost code group should create grouping category, , select models contains summary of given cost code/category group. here sample anonymous types:
var query = t in db.current_jct_transaction             group t t.cost_code g             orderby g.key ascending             select new             {                 costcode = g.key,                 total = g.sum(t => t.amount),                 categories =                      t in g                     group t t.category cg                     select new                     {                         costcode = g.key,                         category = cg.key,                         amount = cg.sum(t => t.amount)                     }             };   output:
[   {     "costcode": 1001,     "total": 420.0,     "categories": [        { "costcode": 1001, "category": "e", "amount": 100.0 },       { "costcode": 1001, "category": "l", "amount": 200.0 },       { "costcode": 1001, "category": "oh", "amount": 120.0 }     ]   },   {     "costcode": 1002,     "total": 400.0,     "categories": [       { "costcode": 1002, "category": "l", "amount": 100.0 },       { "costcode": 1002, "category": "lb", "amount": 100.0 },       { "costcode": 1002, "category": "oh", "amount": 200.0 }     ]   } ]      
Comments
Post a Comment