我写了一个小的linq查询,目前无法编译
LogException()
我的问题是我无法在var count = (from data in Data
join data2 in Data on data.UserId equals data2.UserId
group data2 by data2.UserId into gr
where gr.Max(b => b.Date) == data.Date // data variable not available
select data.Id).Count(); // data variable not available
子句之后重用 data 变量。我该如何实现?
有关信息,这是我要转换的group by
查询。
SQL
答案 0 :(得分:1)
正如我在评论中提到的,您的linq查询中group by
和join
的顺序与您的SQL查询不匹配。
如果您喜欢查询语法,则查询可能如下所示:
(from d in Data
join g in
(from d in Data
group d by d.UserId
into gr
select new { UserId = gr.Key, MaxDate = gr.Max(d => d.Date) })
on new { ID = d.UserId, Date = d.Date} equals new { ID = g.UserId, Date = g.MaxDate }
select d.Id)
.Count();
但这很丑陋,太复杂了。如果要在内存中(linq-to-objects)进行此操作,则需要注意很多分配。
答案 1 :(得分:-4)
尝试以下操作:
var max = (from data in Data
join data2 in Data on data.UserId equals data2.UserId
select new {data = data, data2 = data2})
.GroupBy(x => x.data2.UserId)
.Select(x => x.Max(b => b.data2.Date))
.ToList();