假设我在 Sql 中有以下查询
select UserID,count(distinct ip) as NumberOfIPUsed from UserLogs
group by UserID
我想用林克写这个
好吧,首先你要按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()})
您需要使用在理解表达式中无法直接使用的 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();