我正在使用LINQ加入这两个表来匹配模型类,如下所示
lstOptInInterest = new LinkedList<OptInInterestArea>
((from a in dbEntities.SUBCODE
from appCode in dbEntities.CODE.Where(
x => x.CODE == a.CODE && x.TYPE == a.TYPE)
select new OptInInterestArea()
{
Code = a.CODE,
SubCode = a.SUBCODE,
SubCodeDescription = a.DESCR,
CodeDescription = appCode.DESCR
}).ToList());
public class OptInInterestArea
{
[DisplayName("Code")]
public string Code { get; set; }
[DisplayName("Sub Code")]
public string SubCode { get; set; }
DisplayName("Sub Code Description")]
public string SubCodeDescription { get; set; }
[DisplayName("Code Description")]
public string CodeDescription { get; set; }
[DisplayName("Previous OptIn")]
public bool PrevOptIn { get; set; }
}
现在我的问题是我需要从表B中分配PrevOptIn
lstOptInInterest
的值(见上文)。表B可能包含也可能不包含CODE
的所有SUBCODE
和lstOptInInterest
。
如果表格B中存在CODE
和SUBCODE
lstOptInInterest
,则分配给PrevOptIn
中的PrevOptIn = N
我如何做LINQ才能得到这个?
答案 0 :(得分:1)
首先,我建议您使用INNER JOIN
代替CROSS JOIN
来查询您的lstOptInInterest:
lstOptInInterest = new LinkedList<OptInInterestArea>
((from a in dbEntities.SUBCODE
join appCode in dbEntities.CODE
on new {CODE=a.CODE,TYPE=a.TYPE} equals new {CODE=x.CODE,TYPE=x.TYPE}
select new OptInInterestArea()
{
Code = a.CODE,
SubCode = a.SUBCODE,
SubCodeDescription = a.DESCR,
CodeDescription = appCode.DESCR
}).ToList());
seconde,使用LEFT OUT JOIN
从表B中分配lstOptInInterest的PrevOptIn值:
lstOptInInterest = new LinkedList<OptInInterestArea>
(
(from a in lstOptInInterest
join b in dbEntities.TableB
on new {CODE=a.Code,SUBCODE=a.SubCode} equals new {CODE=b.CODE,SUBCODE=b.SUBCODE}
into leftGroup
from b in leftGroup.DefaultIfEmpty()
select new OptInInterestArea()
{
Code = a.Code,
SubCode = a.SubCode,
SubCodeDescription = a.SubCodeDescription,
CodeDescription = a.CodeDescription,
PrevOptIn=b==null? false : b.OPTIN=="Y"
}).ToList()
);
<强>更新强> 尝试只测试一步以获得结果:
lstOptInInterest = new LinkedList<OptInInterestArea>
((from a in dbEntities.SUBCODE
join appCode in dbEntities.CODE
on new {CODE=a.CODE,TYPE=a.TYPE} equals new {CODE=x.CODE,TYPE=x.TYPE}
join b in dbEntities.TableB
on new {CODE=a.CODE,SUBCODE=a.SUBCODE} equals new {CODE=b.CODE,SUBCODE=b.SUBCODE}
into leftGroup
from b in leftGroup.DefaultIfEmpty()
select new OptInInterestArea()
{
Code = a.CODE,
SubCode = a.SUBCODE,
SubCodeDescription = a.DESCR,
CodeDescription = appCode.DESCR,
PrevOptIn=b==null?false : b.OPTIN=="Y"
}).ToList());