繁体   English   中英

LINQ:将LET分组并包含在最终结果中

[英]LINQ: Group and include the LET in the final result

我将继续LINQ:Groupby和Last

基本上我有下表:

ID  Field1  Field2      Field3
1   aaaa    20/01/2014  10
2   aaaa    21/01/2014  3
3   aaaa    25/01/2014  10
4   bbbb    01/01/2014  90
5   bbbb    03/01/2014  10
6   bbbb    31/01/2014  5

我想按Field1分组,并在Field2的基础上抓取每个组中最早的一行。

我还需要基于field3构建一些复杂的计算(为此,我使用“ let”)。 现在,我在Where子句中使用“ let”。 一切都很好。

我有:

var result = from p in Table1
let MyLet = p.Field3 - 1 //This is actually very complex in the real scenario.
Where MyLet > 5
group p by p.Field1 into grp
select grp.OrderByDescending(g=>g.Field2).First();

现在...如何将MyLet包含到最终结果中,所以看起来像这样

ID  Field1  Field2      Field3 MyLet
3   aaaa    25/01/2014  10     9
5   bbbb    03/01/2014  10     9

尝试这个:-

  var result = from p in fields
                     let MyLet = p.Field3 - 1
                     where MyLet > 5
                     group new { p, MyLet } by p.Field1 into grp
                     let firstField = grp.OrderByDescending(x => x.p.Field2).First()
                     select new
                         {
                             ID = firstField.p.ID,
                             Field1 = firstField.p.Field1,
                             Field2 = firstField.p.Field2,
                             Field3 = firstField.p.Field3,
                             MyLet = firstField.MyLet
                         };

在访问字段之前,请考虑检查Null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM