Linq Group by / Distinct with Join table
Linq Group by / Distinct with Join table
我打算加入 2 table,并获取语言列的不同值。我应该如何在 Linq 中实现这一点?我尝试添加 'group' 但没有运气。此外,我也想 select 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());
}
你可以这样做:
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;
这就是 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();
但我想知道这是否真的是您想要的。结果取决于数据库碰巧 return 的语言顺序。我认为您应该为特定语言添加谓词并删除分组:
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 };
我打算加入 2 table,并获取语言列的不同值。我应该如何在 Linq 中实现这一点?我尝试添加 'group' 但没有运气。此外,我也想 select 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());
}
你可以这样做:
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;
这就是 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();
但我想知道这是否真的是您想要的。结果取决于数据库碰巧 return 的语言顺序。我认为您应该为特定语言添加谓词并删除分组:
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 };