Linq Group by /与联合表格不同 [英] Linq Group by / Distinct with Join table
问题描述
我的代码:
public ActionResult QuestionLink(int Survey_ID)
{
var query = from r in db.SURV_Question_Ext_Model
在db.SURV_Question_Model中加入s
在r上。 Qext_Question_ID等于s.Question_ID
其中s.Question_Survey_ID == Survey_ID
组r.language<<这是行不通的**
select r;
返回PartialView(query.ToList());
这就是 MoreLinq 被称为 DistinctBy
。但是,如果该方法适用于 IEnumerable
,那么您无法在EF查询中使用它。但您可以使用相同的方法:
var query = from db in db.SURV_Question_Ext_Model
在db中加入s。 R.Qext_Question_ID上的SURV_Question_Model等于s.Question_ID
其中s.Question_Survey_ID == Survey_ID
由r.language将group new {r,s}分为grp
select grp.FirstOrDefault();
但我想知道这是否真的是你想要的。结果取决于数据库恰好返回的语言的顺序。我认为您应该为特定语言添加一个谓词并删除分组:
var query = from db in db.SURV_Question_Ext_Model
加入s在db.SURV_Question_Model
上r.Qext_Question_ID等于s.Question_ID
其中s.Question_Survey_ID == Survey_ID
&& r.language == someVariable
选择新的{r,s};
i plan to join 2 table, and get the distinct value of language column. How should i achieve that in Linq? I try add 'group' but no luck. Besides, i want to select s value too together with r distinct language value.
My code:
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());
}
This is what in MoreLinq is called DistinctBy
. But if that method works on IEnumerable
, so you can't use it in an EF query. But you can use the same approach:
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();
But I wonder if this really is what you want. The result depends on the ordering of languages that the database happens to return. I think you should add a predicate for a specific language and remove the grouping:
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 };
这篇关于Linq Group by /与联合表格不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!