Linq to SQL — Group by

需求是需要统计数据库中表某一列的总数量,同时以List的形式返回到UI层。

Linq to SQL中的Group by用法如下:

IList<Unit.HandleCountClass> result;

result = (from a in db.handleinfo_users
             group a by a.han_Server into g
             select new HandleCountClass
              {
                    type = g.Key,
                    Handlecount = g.Count()
               }).ToList();

<补充说明>
1、返回的格式是List,它的参数形式是某个对象,但由于是统计Count()后的总数量,现有的对象类中没有可以满足的,所以我在Unit共用层定义一个HandleCountClass的类,类的结构代码会在后面进行介绍。

2、g.key指的就是Group by的字段名,如在我的这个例子当中,就是han_Server字段。

HandleCountClass类:

    public class HandleCountClass
    {
        public string type;
        public int Handlecount;
    }

相应的SQL代码如下:

select han_Server,COUNT(han_Server) as Servercount from handleinfo_users
group by han_Server
原文地址:https://www.cnblogs.com/guolebin7/p/2862991.html