c# - Help with LINQ-SQL GroupBy -
i'm trying convert t-sql linq-sql query:
-- top 3 pros city select top 3 description, ispro, count(*) numberofvotes tblprocon idprimarycity = @idprimarycity , ispro = 1 group idprimarycity, ispro, description union -- top 3 cons city select top 3 description, ispro, count(*) numberofvotes tblprocon idprimarycity = @idprimarycity , ispro = 0 group idprimarycity, ispro, description order ispro, numberofvotes desc
here's have far:
// construct base query var query = (from p in db.tblprocons p.idprimarycity == idprimarycity group p new { p.idprimarycity, p.ispro, p.description } g select new { description = g.key, ispro = g.any(x => x.ispro), numberofagrees = g.count() }); // split queries based on pro/con, , apply top(3) var pros = query.where(x => x.ispro).take(3); var cons = query.where(x => !x.ispro).take(3); result = pros .union(cons) // union pro/cons .orderbydescending(x => x.ispro) // order #1 - pro/con .thenbydescending(x => x.numberofagrees) // order #2 - number of agree's .select(x => new procon // project cut-down poco { description = x.description, ispro = x.ispro }).tolist();
but ain't working. :(
x.description
complaining "cannot convert source type {idprimarycity:int, ispro:bool, description:string} target type string".
all want end list<procon>
, having description (string), , flag indicating if it's pro or con.
what doing wrong?
nevermind, got it, "group" projection wrong.
here's working solution:
// construct base query var query = (from p in db.tblprocons p.idprimarycity == idprimarycity group p new { p.idprimarycity, p.ispro, p.description } g select new { procon = g.key, numberofagrees = g.count() }); // split queries based on pro/con, , apply top(3) var pros = query.where(x => x.procon.ispro).take(3); var cons = query.where(x => !x.procon.ispro).take(3); result = pros .union(cons) // union pro/cons .orderbydescending(x => x.procon.ispro) // order #1 - pro/con .thenbydescending(x => x.numberofagrees) // order #2 - number of agree's .select(x => new procon // project cut-down poco { description = x.procon.description, ispro = x.procon.ispro }).tolist();
Comments
Post a Comment