我不理解linq。我不知道为什么。
我有三张桌子。1)TillTable
tillId, tillName
1 w1
2 w2
3 w3
4 w4
2)TillDepartment
tillDeptId, tillId, deptId, isPart
1 1 5 1
2 1 7 0
3 1 8 0
4 1 9 0
5 2 5 0
6 2 7 0
7 2 8 0
8 2 9 0
9 3 5 0
10 3 7 1
11 3 8 0
12 3 9 0
13 4 5 0
14 4 7 0
15 4 9 0 so on....
3)departmentTable
deptId, deptName
5 Science
7 Commerce
8 history
9 English so on....
现在使用linq或lambda exp我想显示以下结果,
tillId, tillName, deptName
1 w1 science
2 w2 no dept
3 w3 commerce
4 w4 no dept so on...
我希望linq掌握其该死的轻松任务....
帮助我解决它....
如果isPart列为1,那么在结果集中,deptName应该显示在其他地方' no dept' ....
关联表有多个条目,用于tillId .....
它的要求严格遵循这种情况......
我希望它能够......
答案 0 :(得分:0)
试试这个: -
var result = (from tt in db.tillTables
join td in db.tillDepts
on tt.tillId equals td.tillId
join dt in db.departmentTable
on td.deptid equals dt.deptId
select new
{
tillId = tt.tillId,
tillName = tt.tillName,
deptName = td.isPart == 1 ? dt.deptName : null
}).GroupBy(x => x.tillId)
.Select(x =>
{
var orderedDeptRecord = x.OrderByDescending(z => z.deptName).FirstOrDefault();
return new
{
tillId = x.Key,
tillName = orderedDeptRecord.tillName,
deptName = orderedDeptRecord.deptName
};
});
答案 1 :(得分:0)
外连接到单个记录,然后,deptName的外键是带有三元运算符的select子句(被转换为" case")
from t in TillTable
join tds in TillDepartment on new { t.tillId,isPart=1}
equals new { td.tillId, isPart } into tdOuter
from td in tdOuter.DefaultIfEmpty().Take(1)
select new { t.tillId, t.tillName,
deptName=((td==null)? "no dept" :
(from dt in departmentTable
where dt.deptId == td.deptId
select deptName ) ) }