如何在实体框架C#中使用多个Group By?
我有一个为多个group by编写的SQL查询如何在实体框架C#中使用多个Group By?,c#,asp.net-mvc,entity-framework,linq,C#,Asp.net Mvc,Entity Framework,Linq,我有一个为多个group by编写的SQL查询 select COUNT(Count) as Count, City,State,ZipCode from ZipSearchHistories Group By City,State,ZipCode 现在我需要将这个SQL查询更改为实体框架。到目前为止我所尝试的是 var result = await repository.GetAllAsync(); var data = from m in result
select COUNT(Count) as Count, City,State,ZipCode from ZipSearchHistories Group By City,State,ZipCode
现在我需要将这个SQL查询更改为实体框架。到目前为止我所尝试的是
var result = await repository.GetAllAsync();
var data = from m in result
group m by m.City, m.State,m.ZipCode into g
let Count = g.Count()
orderby Count descending
select new { Count= Count,City = m.City,State = m.State, ZipCode = m.ZipCode}
但它不起作用。我如何解决这个问题呢?所以你有一系列的
ZipSearchHistories
。此序列中的每个ZipSearchHistory至少有一个ZipCode、一个州和一个城市
其中一些ZipSearchHistory对{ZipCode,State,City}具有相同的值。您希望为{ZipCode,State,City}的每个组合计算具有此组合的ZipSearchHistory的数量
你是对的,这是你需要的。我经常使用带有参数resultSelector的重载。使用此参数可以指定每组的输出
var result = dbContext.ZipSearchHistories(
// parameter keySelector: make groups with same values for {ZipCode, State, City}
zipSearchHistory => new
{
ZipCode = zipSearchHistory.ZipCode,
State = zipSearchHistory.State,
City = zipSearchHistory.City,
},
// parameter resultSelector: for every key {ZipCode, State, City},
// and all ZipSearchHistories that have this {ZipCode, State, City} make one new:
(key, zipSearchHistoriesWithThisKey) => new
{
ZipCode = key.ZipCode,
State = key.State,
City = key.City,
Count = zipSearchHistoriesWithThisKey.Count(),
})
换句话说:创建ZipSearchHistories组,这些组对{ZipCode,State,City}具有相同的值。从每个组(其中所有元素都有这个{ZipCode,State,City})创建一个新对象,这个对象有这些{ZipCode,State,City}和组中元素的数量。定义“没有工作”。它抛出了一个错误吗?然后分享它。它是否与您预期的数据分组不同?然后分享你的期望和发生的事情。这能回答你的问题吗@franzgleichman它说的是不正确的语法。对于LINQ,你需要使用类型“分组方式”,例如
.GroupBy(m=>new{m.City,m.State,m.ZipCode})
。但是当你问问题时,你应该总是复制/粘贴准确的错误!,作为将来的参考:)@BirazDahal那么逻辑步骤应该是在手册中检查正确的语法。例如,谷歌搜索“LinqGroupbySyntax”就得到了第一个结果。