2010-11-16 4 views
0

Je suis en train de convertir ce T-SQL pour une requête LINQ-SQL:Aide LINQ-SQL GroupBy

-- 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 

Voici ce que j'ai jusqu'à présent:

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

Mais elle ain ne travaille pas. :(

x.Description se plaint "Impossible de convertir le type de source {IdPrimaryCity: int, ISPRO: bool, Description: string} pour cibler la chaîne de type".

Tout ce que je veux retrouver avec un List<ProCon>, ayant la description (string), et le drapeau indiquant si elle est un pro ou con.

Qu'est-ce que je fais mal?

Répondre

1

de Nevermind, je l'ai eu, la projection était tout faux.

"groupe" Voici la solution de travail tion:

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