简体   繁体   English

linq分组和计数

[英]linq group by and count

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(*)

And here is what I've tried: 这是我尝试过的:

 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;
        }

how can I achieve what I need? 我怎样才能达到我所需要的?

The key of the dictionary is the key of the GroupBy and the value is the Count() , so you need: 字典的键是GroupBy的键,值是Count() ,因此您需要:

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

Since you've asked how to order it decending: 既然您已经问过如何以降序排列:

You are building a dictionary which has no order(well, It should read: it is non-deterministic). 您正在建立没有顺序的字典(嗯,它应该读为:它是不确定的)。 So the ordering is completely unnecessary. 因此,订购完全没有必要。 Why it's unordered? 为什么它是无序的? Read this 读这个

But if you would create something else and you wanted to know how to order by Count DESC you could use 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() })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM