我计划连接2个表,并获得语言列的唯一值。我应该如何实现在Linq?我试着添加"group",但没有成功。此外,我还想选择s值和r不同的语言值。
我代码: public ActionResult QuestionLink(int Survey_ID)
{
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group r.language << this is not work **
select r;
return PartialView(query.ToList());
}
这就是MoreLinq中所谓的DistinctBy
。但是如果这个方法在IEnumerable
上工作,那么你就不能在EF查询中使用它。但是您可以使用相同的方法:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.language into grp
select grp.FirstOrDefault();
但我想知道这是不是你想要的。结果取决于数据库碰巧返回的语言的顺序。我认为您应该为特定语言添加谓词并删除分组:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
&& r.language == someVariable
select new { r, s };
你可以这样做:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new {r, s} by r.language into rg
select rg.Key;