linq group by and count

时间:2016-09-02 07:49:05

标签: c# asp.net linq

select  uc.adminid, count(*)
from Users uc
join UsersMessage ucm on uc.admincallid = ucm.admincallid
where uc.CallDate between '2016-08-01' and '2016-09-01' and ucm.type = 4
group by uc.adminid
order by count(*)

以下是我的尝试:

 public static Dictionary<int, int> ReturnSomething(int month)
        {

            Dictionary<int, int> dict = new Dictionary<int, int>();
            using (DataAccessAdapter adapter = new DataAccessAdapter())
            {
                LinqMetaData meta = new LinqMetaData(adapter);
                dict = (from uc in meta.Users
                        join ucm in meta.meta.UsersMessage on uc.AdminCallId equals ucm.AdminCallId 
                        where ucm.type == 4 && uc.CallDate.Month == month
                        group uc by uc.AdminId into g
                        select new { /* ???? adminid = g. */ }).ToDictionary(x => new Dictionary<int, int>(/* ????? x, x.Name*/));
            }

            return dict;
        }

我怎样才能实现我的需要?

1 个答案:

答案 0 :(得分:2)

字典的键是GroupBy的键,值是Count(),所以你需要:

// ...
.ToDictionary(g => g.Key, g => g.Count()); // key is AdminCallId and value how often this Id occured

因为您已经询问如何订购它降序:

您正在构建一个没有顺序的字典(好吧,它应该是:它是非确定性的)。所以排序是 完全没必要。它为什么无序? Read this

但是,如果你想创建其他东西并想知道如何通过Count DESC订购,你可以使用它:

from uc in meta.Users
join ucm in meta.meta.UsersMessage on uc.AdminCallId equals ucm.AdminCallId 
where ucm.type == 4 && uc.CallDate.Month == month
group uc by uc.AdminId into g
orderby g.Count() descending
select new { adminid = g.Key, count = g.Count() })