【问题标题】:Linq Group by / Distinct with Join tableLinq Group by / Distinct with Join 表
【发布时间】:2015-06-03 09:01:17
【问题描述】:

我计划加入 2 个表,并获取语言列的不同值。我应该如何在 Linq 中实现这一点?我尝试添加“组”,但没有运气。此外,我也想选择 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());
        } 

【问题讨论】:

  • 你期待什么结果?

标签: linq join group-by distinct


【解决方案1】:

这就是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 };

【讨论】:

  • 感谢您的反馈。是否可以选择 2 个值,即 select grp.FirstOrDefault 和 r ?
  • 对不起@gert arnold,我的错,我也想要 select s。可能类似于 select new {grp.FirstOrDefault() , s } ?
  • 另一方面,如果SURV_Question_Ext_ModelSURV_Question_Model 通过导航属性相关联,那可以改进一些事情。
【解决方案2】:

你可以这样做:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2016-12-04
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多