我有两张表Task
和EmpTask
。
Table: Task Table: EmpTask
__________ ________________________
ID | Title ID | TaskID | XXXX
__________ ________________________
1 | task1 1 | 1 | emptask1
2 | task2 2 | 1 | emptask2 (this is last occurance of taskID 1)
__________ 3 | 2 | emptask3
4 | 2 | emptask4 (this is last occurance of taskID 2)
________________________
预期结果:
________________________
ID | Title | XXXX
________________________
1 | task1 | emptask2
2 | task2 | emptask4
________________________
我想要帮助在Lambda表达式中编写查询。
提前致谢。
答案 0 :(得分:2)
假设您想要max EmpTask
。
var result = (from t in db.Task
join r in db.EmpTask
.GroupBy(i => i.TaskID)
.Select(i => new { TaskID = i.Key, EmpTaskId = i.Max(t => t.ID)})
on t.ID equals r.TaskID
join et in db.EmpTask on r.EmpTaskId equals et.ID
select new
{
ID = t.ID,
Title = t.Title,
XXXX = et.XXXX
}).ToList();
Lambda Expression
var result = db.Task.Join(
db.EmpTask
.GroupBy(i => i.TaskID)
.Select(i => new { TaskID = i.Key, EmpTaskId = i.Max(t => t.ID)})
,
t => t.ID,
r => r.TaskID,
(t, r) => new { Task = t, EmpTaskTmp = r}
).Join(
db.EmpTask,
et => et.ID
y => y.EmpTaskTmp.EmpTaskId,
(et, y) => new { Task = y.Task, MaxEmpTask = et}
).Select(i => new
{
ID = i.Task.ID,
Title = i.Task.Title,
XXXX = i.MaxEmpTask.XXXX
});
答案 1 :(得分:0)
我管理得到答案。谢谢大家的帮助:)
var result = db.Task.Join(db.EmpTask, t => t.ID, et => et.TaskID, (t, et) => new { t, et })
.Select(m => new
{
ID = m.t.ID,
Title = m.t.Title,
XXXX= m.et.XXXX
}).GroupBy(m => m.ID, (key, g) => g.OrderByDescending(m => m.EmpTaskId).FirstOrDefault()).ToList();