具有聚合和分组依据的LINQ查询

时间:2012-10-17 19:21:45

标签: c# linq entity-framework

我有以下SQL查询...

    select  seaMake AS Make,
        seaModel AS Model,
        COUNT(*) AS [Count],
        MIN(seaPrice) AS [From],
        MIN(seaCapId) AS [CapId]
from tblSearch 
where seaPrice >= 2000
and seaPrice <= 7000
group by seaMake, seaModel
order by seaMake, seaModel

我试图将其写为LINQ to Entities Query,但我遇到了问题。这是我到目前为止,但我无法访问var S

中的品牌和型号值
var tester = from s in db.tblSearches
             where s.seaPrice >= 2000
             && s.seaPrice <= 7000
             orderby s.seaMake
             group s by s.seaMake into g
             select new
             {
                 make = g.seaMake,
                 model = s.seaModel,
                 count = g.Max(x => x.seaMake),
                 PriceFrom = g.Min(s.seaPrice)
              };

我哪里错了?

2 个答案:

答案 0 :(得分:2)

这应该是SQL的直接翻译:

from s in db.tblSearches
where
    s.seaPrice >= 2000 &&
    s.seaPrice <= 7000
group s by new {s.seaMake, s.seaModel} into g
orderby g.Key
select new
{
    Make =  g.Key.seaMake,
    Model = g.Key.seaModel,
    Count = g.Count(),
    From =  g.Min(x => x.seaPrice),
    CapId = g.Min(x => x.seaCapId)
}

答案 1 :(得分:1)

分组为 g时,您将该集合转换为IEnumerable&gt;而不是原始的IEnumerable<TypeOfS>集合。所以当前范围内的集合是g。所以以下内容是有效的

from s in db.tblSearches
where s.seaPrice >= 2000
   && s.seaPrice <= 7000
orderby s.seaMake
group s by s.seaMake into g // the collection is now IEnumerable<IGrouping<TypeOfSeaMake, TypeofS>>
select new {
    make = g.Key, // this was populated by s.seaMake
    model = g.First().seaModel, // get the first item in the collection
    count = g.Max(x => x.seaMake), // get the max value from the collection
    PriceFrom = g.Min(x => x.seaPrice), // get the min price from the collection
};

现在将为每个分组返回一个项目