C# LINQ-SQL GroupBy的帮助
我正在尝试将此T-SQL转换为LINQ-SQL查询:C# LINQ-SQL GroupBy的帮助,c#,tsql,linq-to-sql,group-by,C#,Tsql,Linq To Sql,Group By,我正在尝试将此T-SQL转换为LINQ-SQL查询: -- top 3 pros for city select top 3 description, ispro, COUNT(*) as numberofvotes from tblProCon where IdPrimaryCity = @IdPrimaryCity and IsPro = 1 group by IdPrimaryCity, IsPro, description union -- top 3 cons for city s
-- top 3 pros for city
select top 3 description, ispro, COUNT(*) as numberofvotes
from tblProCon
where IdPrimaryCity = @IdPrimaryCity
and IsPro = 1
group by IdPrimaryCity, IsPro, description
union
-- top 3 cons for city
select top 3 description, ispro, COUNT(*) as numberofvotes
from tblProCon
where IdPrimaryCity = @IdPrimaryCity
and IsPro = 0
group by IdPrimaryCity, IsPro, description
order by ispro, numberofvotes desc
以下是我目前掌握的情况:
// Construct base query
var query = (from p in db.tblProCons
where p.IdPrimaryCity == idPrimaryCity
group p by new { p.IdPrimaryCity, p.IsPro, p.Description } into g
select new { Description = g.Key, IsPro = g.Any(x => x.IsPro), NumberOfAgrees = g.Count() });
// Split queries based on pro/con, and 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 into cut-down POCO
{
Description = x.Description,
IsPro = x.IsPro
}).ToList();
但她没有工作(
x.Description
抱怨“无法将源类型{IdPrimaryCity:int,IsPro:bool,Description:string}转换为目标类型string”
我只想得到一个列表
,上面有描述(字符串)和标志,指示它是赞成还是反对
我做错了什么?没关系,我明白了,“团体”投影完全错了
以下是可行的解决方案:
// Construct base query
var query = (from p in db.tblProCons
where p.IdPrimaryCity == idPrimaryCity
group p by new { p.IdPrimaryCity, p.IsPro, p.Description } into g
select new { ProCon = g.Key, NumberOfAgrees = g.Count() });
// Split queries based on pro/con, and 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 into cut-down POCO
{
Description = x.ProCon.Description,
IsPro = x.ProCon.IsPro
}).ToList();