.NET Linq加入

我在SQL中有2个表。

Table 1 Step Id Step Name Table 2 Profile Id Step Id Completed 

即使表2中没有匹配,我也想返回以下结果:

 Results Table1.Step Id Table1.Step Name Table2.Profile Id Table2.Completed 

我在SQL中执行此操作的方式如下:

 select * from [Table 1] t1 left join [Table 2] t2 on t1.Step Id = t2.Step Id 

这产生了我期望的结果。

当我把它翻译成linq时:

 public static List GetStepCompletion(string category, string profileid) { List step = GetSteps(category); List userStep = GetUserSteps(category, profileId); var q = from s in step join us in userStep on s.Id equals us.StepId select new UserCompletion { StepId = s.Id, Headline = s.StepName, ProfileId = us.ProfileId Completed= us.Completed }; return q.ToList(); } 

它可以工作,但像JOIN而不是左连接。 我只收到匹配的结果。

此外,UserCompletion是我从此方法返回的对象。

我已经在这里敲了几天……任何帮助都会受到赞赏。

你也可以尝试这个(假设us.Completed是布尔值):

 var q = from s in step let us = (from i in userStep where s.Id = i.StepId).SingleOrDefault() select new UserCompletion { StepId = s.Id, Headline = s.StepName, ProfileId = us.ProfileId Completed = us == null ? false : us.Completed }; 

这不会变成sql中的连接,而是嵌套的select语句,如下所示:

 select StepId, Headline, ProfileId, isnull((select top(1) Completed from userStep where StepId = Id), 0) as Completed from step 

尝试以下几点:

 var q = from s in step join us in userStep on s.Id equals us.StepId into tmpjoin from x in tmpjoin.DefaultIfEmpty() select new UserCompletion { ... } 

找到了。

好像我需要在“可能”为null的项目上添加评估。

我在选择中添加了以下内容

 Completed = (x == null) ? String.Empty : x.Completed