首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Lambda表达式中使用Max、Group、Join和Where

在Lambda表达式中使用Max、Group、Join和Where
EN

Stack Overflow用户
提问于 2016-03-03 14:27:57
回答 2查看 1.9K关注 0票数 0

我尝试使用Lambda表达式(而不是对我)进行复杂的查询。我有我想要“翻译”到Lambda的SQL。

代码语言:javascript
运行
复制
SELECT MAX((SUBSTRING(tbp.dt,4,4)+SUBSTRING(tbp.dt,2,2)+SUBSTRING(tbp.dt,1,2))) as Dt, 
tb._n, tbp.number, tbp.dsc
FROM TB_A tb
JOIN TB_B_C tbp ON tbp.number = tb.number
WHERE tbp.rec = 0 AND tbp.processing = 0 AND tb._n != '' AND tbp.error = 0
GROUP BY tb._n, tbp.number, tbp.dsc

到目前为止,我有一个Lambda表达式:

代码语言:javascript
运行
复制
var results = db.a
           .Join(db.b_c, proc => proc.number, andam => andam.number, (proc, andam) => new { proc, andam })
           .Where(d => d.proc._n != "" && d.andam.rec == false && d.andam.processing == false && d.andam.error)
           .ToList();

如何完成选择以获得与SQL查询相同的结果?如果可能的话,您能解释一下在将查询“翻译”到Lambda时如何正确地思考吗?

非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-03 14:57:56

使用查询语法编写通常更容易

代码语言:javascript
运行
复制
var results = from tb in db.a
              join tbp in db.b_c on tb.number equals tbp.number
              where tbp.rec == 0 
                    && tbp.processing == 0 
                    && tb._n != string.Empty 
                    && tbp.error == 0
              group new {tb, tbp}  by new {tb._n, tbp.number, tbp.dsc} into grp
              select new
              {
                  grp.Key._n,
                  grp.Key.number,
                  grp.Key.dsc,
                  Dt = grp.Max(x => x.tbp.dt.Substring(4,4) 
                                  + x.tbp.dt.Substring(2,2) 
                                  + x.tbp.dt.Substring(0,2))
              };
票数 1
EN

Stack Overflow用户

发布于 2016-03-07 16:29:56

你所需要做的就是

1)添加GroupBySelect语句

2)将Join替换为GroupJoin

下面的示例与数据库架构无关.

选项1)

代码语言:javascript
运行
复制
var results = ...
           .GroupBy(x=> new {x.Field1, x.Field2, x.Field3})
           .Select(grp=>new
            {
               Key = grp.Key,
               MaxVal = grp.Max(o=>o.Field1)
            });

选项2)

代码语言:javascript
运行
复制
var result = db_a.Where(x=>x.Field1==1 && x.Field2==0)
            .GroupJoin(db_b.Where(x=>x.Field3==5),
                       a => a.PrimaryKey,
                       b => b.ForeignKey,
                       (a, b) => new
                           {
                               PK=a.PrimaryKey,
                               MaxVal=b.Max(o=>o.Field2)
                            });

来源:https://msdn.microsoft.com/en-us/library/bb534297%28v=vs.110%29.aspx

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35774883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档