Linq组按和计数

本文关键字:Linq | 更新日期: 2023-09-27 18:05:13

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

我怎样才能达到我所需要的?

Linq组按和计数

字典的键是GroupBy的键,值是Count(),因此需要:

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

既然你问如何排序,降序:

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

但是如果你想创建其他东西,你想知道如何通过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() })