我正在尝试将此linq查询转换为lambda
var query = (from a in context.Table_A
join u in context.Table_B on a.scored equals u.userid
join u2 in context.Table_B on a.scorer equals u2.userid
from cs in a.Table_C //(Table_A is related to Table_C)
where (a.date>= startdate && a.date < enddate)
select new MSViewModel
{
scored= u.User.name,
scorer= u2.User.name,
subject_name = cs.Subject.name,
score = cs.score,
categoryid = cs.id,
})
.AsEnumerable()
.GroupBy(t => t.scored)
.ToList();
到目前为止,这就是我所拥有的。我有点失去下一步该做什么。
var tobi = db.Table_A.Join(db.Table_B,a=>a.scored,u=>u.userid,
(a,u) => new {scored=u.User.name });
db.Table_A.Join(db.Table_B,a1=>a1.scorer,u2=>u2.userid,
(a,u2)=> new {scorer= u2.User.name});
答案 0 :(得分:14)
首先,我同意Arran的评论:查询表达式将更容易处理。我绝对认为使用lambda表单是有意义的,但是在查询表达式中,连接通常很多更简单。
话虽如此,你基本上需要模仿transparent identifiers。下面的代码未经测试,但对我来说看起来很模糊。
var query = context.Table_A
.Join(context.Table_B, a => a.scored, u => u.userid,
(a, u) => new { a, u })
.Join(context.Table_B, p => p.a.scorer, u2 => u2.userid,
(p, u2) => new { p, u2 })
.SelectMany(q => q.p.a.TableC, (q, cs) => new { q, cs })
.Where(r => r.q.p.a.date >= startdate && r.q.p.a.date < enddate)
.Select(q => new MSViewModel {
scored= r.q.p.u.User.name,
scorer= r.q.u2.User.name,
subject_name = r.cs.Subject.name,
score = r.cs.score,
categoryid = r.cs.id,
})
.AsEnumerable()
.GroupBy(t => t.scored)
.ToList();
基本上p
和q
以及r
是透明标识符。你有三个,因为你有两个连接和一个后续的from
子句。
答案 1 :(得分:4)
要扩展我的评论,如果你有Resharper:
Resharper显示将LINQ转换为Lambada 的选项
转化后:
答案 2 :(得分:2)
试试这个:
var query = (_context.Table_A.Join(_context.Table_B, a => a.scored, u =>
u.userid,
(a, u) => new {a, u}).Join(_context.Table_B,
@t => @t.a.scorer,
u2 => u2.userid,
(@t, u2) => new {@t, u2}).
SelectMany(@t => _context.Table_A, (@t, cs) => new MSViewModel()
{
scored = @t.@t.u.User.name,
scorer= @t.u2.User.name,
subject_name = @t.cs.Subject.name,
score = @t.cs.score,
categoryid = @t.cs.id,
})).AsEnumerable()
.ToList();