LINQ to SQL GroupBy,Take和OrderBy

时间:2015-10-23 12:00:09

标签: c# linq linq-to-sql lambda group-by

我有一张记录表

|   ID      |   FKID    |   Date        |   Username        |
--------------------------------------------------------------
|   A       |   a1      |   01/01/01    |       Joe         |
|   B       |   a1      |   02/01/01    |       Joe         |
|   C       |   b1      |   03/01/01    |       Joe         |
|   D       |   b1      |   04/01/01    |       Joe         |
|   E       |   c2      |   05/01/01    |       Joe         |
|   F       |   c2      |   06/01/01    |       Joe         |

我想选择3条不同FKID订单的记录,其中最新日期首先属于Joe

|   F       |   c2      |   06/01/01    |       Joe         |
|   D       |   b1      |   04/01/01    |       Joe         |
|   B       |   a1      |   02/01/01    |       Joe         |

我可以为一条记录实现这一目标:

Table.Where(a => a.Username.Equals("Joe"))
     .GroupBy(a => a.FKID)
     .Select(g => g.FirstOrDefault())
     .ToList<Record>();

但无法让Take()OrderByDecending()正常工作。

1 个答案:

答案 0 :(得分:2)

您需要OrderByDescending: -

Table.Where(a => a.Username.Equals("Joe"))
     .GroupBy(a => a.FKID)
     .Select(g => g.OrderByDescending(x => x.Date).FirstOrDefault())
     .Take(3)
     .ToList<Record>();