2015-10-23 59 views
1

我有記錄的LINQ to SQL的GroupBy,採取和排序依據

| 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()才能正常工作。

+0

'。選擇(G => g.OrderBy(d => d.Date).LastOrDefault())' –

回答

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>();