我有主表帐户,ID(PK),CustomerId(FK)和AccountNumber。
客户可以拥有“n”个帐号。
Account
--------
1 | 1 | 93839200
2 | 1 | 93839201
3 | 1 | 93839202
4 | 2 | 93839200
另一个表是AccountStatus,带有Id(PK),AccountId(FK),status和statusDate。
AccountStatus
--------------
1 | 1 | Created | 1/1/2013
2 | 1 | Verified| 2/1/2013
3 | 2 | Created | 9/1/2013
4 | 2 | Rejected| 11/1/2013
5 | 2 | Deleted | 12/1/2013
6 | 3 | Deleted | 12/1/2013
帐户的Satus将插入此表中并带有状态日期。
我需要一个Linq语句来为CustomerID选择最新的Bank状态。
即如果我将CustomerID作为1传递,我需要获得BankAccount的最新状态,如
2 | 1 | Verified| 2/1/2013
5 | 2 | Deleted | 12/1/2013
6 | 3 | Deleted | 12/1/2013
答案 0 :(得分:0)
var results = from a in Accounts
join s in AccountStatuses on a.ID equals s.AccountID
group new { a, s } by a.CustomerID into g
let i = g.OrderByDescending(i => i.s.StatusDate).FirstOrDefault()
select new
{
AccountId = i.a.ID,
CustomerID = i.a.CustomerID,
Status = i.s.Status,
StatusDate = i.s.StatusDate
};