2013-03-20 58 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