Linq Group by /与联合表格不同 [英] Linq Group by / Distinct with Join table

查看:125
本文介绍了Linq Group by /与联合表格不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算加入2张表,并获得语言栏的独特价值。我应该如何在Linq中实现这个目标?我尝试添加组,但没有运气。此外,我想选择s值与r独特的语言价值一起。



我的代码:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆