首页 > 解决方案 > 如何在linq中计算多列数据

问题描述

SELECT country, city, COUNT(school), COUNT(collage) 
FROM T1
GROUP BY country, city

我在 Linq 中写了这个查询

var count_captainRegisterd1 = (from a in dt1.AsEnumerable()
                               group a by new
                               {
                                   oc_name = a.Field<string>("county"),
                                   oc_city = a.Field<string>("city")
                               } into g
                               select new
                               {
                                   g.Key.oc_name,
                                   g.Key.oc_city,
                                   country = g.Count()
                               }
                              ).ToList();

但他们算country列。我想要countrycity两者都算

标签: sqlentity-frameworklinq

解决方案


这是您查询的 linq:

var count_captainRegisterd1 = 
    (from a in dt1.AsEnumerable()
     group a by new
     {
         oc_name = a.Field<string>("county"),
         oc_city = a.Field<string>("city")
     } into g
     select new
     {
          Country = g.Key.oc_name,
          City = g.Key.oc_city,
          SchoolCount = g.Count(r => !string.IsNullOrWhiteSpace(r.Field<string>("school"))),
          CollageCount = g.Count(r => !string.IsNullOrWhiteSpace(r.Field<string>("collage")))
      }).ToList();

推荐阅读