动态Linq按计数分组

时间:2018-06-29 12:34:38

标签: .net asp.net-mvc linq

SQL

 select Country,Count(City) as City from Customers group by Country

控制器     sortable_top =国家,城市

     public ActionResult _Query(List<string> sortable_bot, List<string> sortable_top)
    {
        IQueryable result;
        List<M_Customers> result2;
        string gro = string.Join(",", sortable_top);         
        using (var context = new NwContext())
        {
            result = context.Customers;
            result = result.GroupBy("new (" + gro + ")", "it");
            result2 = result.Select<M_Customers>("new (it.Key as Key , Count(City) as Count)").ToList();
        }
        return PartialView(result2);
    }

我想将这样的SQL查询转换为linq。我收到一条错误消息。

 result2 = result.Select<M_Customers>("new (it.Key as Key , it.Count() as Count)").ToList();

如果我这样写,我将按人数分组,但我不希望这样。 我想要分组城市的数量

2 个答案:

答案 0 :(得分:0)

这样做:

"new (it.Key as Key , Count(City != null) as Count)"

因为在SQL的末尾COUNT(something)的含义类似于SUM(CASE WHEN something IS NOT NULL THEN 1 ELSE 0 END)。请注意,不支持COUNT DISTINCT

答案 1 :(得分:0)

result2 = result.Select<M_Customers>("new (it.Key as Key , it.Select(City).Count() as Count)").ToList();

我这样固定