如何在Linq中编写非重复计数查询

时间:2018-12-20 10:43:19

标签: entity-framework linq sql-to-linq-conversion

假设我在Sql中有以下查询

select UserID,count(distinct ip) as NumberOfIPUsed from  UserLogs 
group by UserID

我希望它与Linq一起写

2 个答案:

答案 0 :(得分:1)

好吧,首先,您要按UserID分组:

UserLogs.GroupBy(ul => ul.UserID)

然后,您要获取用户ID和与此不同的ip的数量:

UserLogs.GroupBy(ul => ul.UserID).Select(g => new {UserID = g.Key, Count = g.Select(ul => ul.ip).Distinct().Count()})

答案 1 :(得分:1)

您需要使用Distinct函数,该函数在理解表达式中不直接可用,因此需要某些函数样式:

var res = await (from ul in context.UserLogs
                 group ul by ul.UserId into grouped
                 select new {
                   UserId = grouped.Key,
                   Count = group.Select(x => x.ip).Distinct().Count()
                 }).ToListAsync();