LINQ:Groupby和Last

时间:2014-09-21 13:46:48

标签: c# linq

我是LINQ的新手。

我有下表:

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  1
6   bbbb    31/01/2014  5

我想按Field1分组并抓住每组的最后一行。 与此等效的SQL查询是:

SELECT Field1, Last(Field2) AS LastOfField2, Last(Field3) AS LastOfField3
FROM Table1
GROUP BY Field1

如何在Linq上实现这一目标?

1 个答案:

答案 0 :(得分:1)

var result = from p in Table1
group p by p.Field1 into grp
select grp.OrderByDescending(g=>g.Field2).First();