2013-03-20 59 views
-3

我有主表帐户,与Id(PK),CustomerId(FK)和AccountNumber。Linq帮助分组表

客户可以拥有“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语句为客户ID选择最新的银行状态。

即如果我通过客户ID为1,我需要得到像

2 | 1 | Verified| 2/1/2013 
5 | 2 | Deleted | 12/1/2013 
6 | 3 | Deleted | 12/1/2013 
+1

显示BankAccount的最新状态它的LINQ to SQL,LINQ到实体或LINQ到对象? – MarcinJuraszek 2013-03-20 10:49:09

回答

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 
       }; 
+0

谢谢它适合我! :) – user2158152 2013-03-20 12:12:08