【问题标题】:Help with LINQ-SQL GroupByLINQ-SQL GroupBy 帮助
【发布时间】:2010-11-16 03:16:32
【问题描述】:

我正在尝试将此 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
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} 转换为目标类型字符串”。

我只想得到一个List<ProCon>,有描述(字符串)和标志,表明它是赞成还是反对。

我做错了什么?

【问题讨论】:

    标签: c# tsql linq-to-sql group-by


    【解决方案1】:

    没关系,我明白了,“组”投影全错了。

    这是有效的解决方案:

    // 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2018-11-24
      • 2014-06-07
      • 1970-01-01
      相关资源
      最近更新 更多