假设我在Sql中有以下查询
select UserID,count(distinct ip) as NumberOfIPUsed from UserLogs
group by UserID
我希望它与Linq一起写
答案 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();