2017-08-10 127 views
1

我有一個包含帳戶餘額歷史的表。我想編寫一個返回每個賬戶最後餘額的Linq查詢。Linq獲取每個元素的最近日期(或最大值)

此時此刻我使用此查詢:

var lastDate = AccountBalances.Max(y => y.BalanceDate); 

var listOfBalance = AccountBalances.Where(y => y.BalanceDate == lastDate).ToList(); 
listOfBalance.Dump(); // FYI I use LinqPad 

但這並不是corretc因爲我不執行每個計算每天帳戶。每個賬戶可以有不同的最後餘額。

例子:

AccountNumber | BalanceDate | Value 
---------------------------------------- 
1234-0001  | 2017-08-08 | 100 
1234-0002  | 2017-08-08 | 250 
1234-0003  | 2017-08-08 | 500 
1234-0004  | 2017-08-08 | 150 
1234-0001  | 2017-08-09 | 110 
1234-0002  | 2017-08-09 | 230 
1234-0003  | 2017-08-09 | 400 
1234-0001  | 2017-08-10 | 120 
1234-0002  | 2017-08-10 | 210 

我的查詢返回此

AccountNumber | BalanceDate | Value 
---------------------------------------- 
1234-0001  | 2017-08-10 | 120 
1234-0002  | 2017-08-10 | 210 

但應該返回

AccountNumber | BalanceDate | Value 
---------------------------------------- 
1234-0001  | 2017-08-10 | 120 
1234-0002  | 2017-08-10 | 210 
1234-0003  | 2017-08-09 | 400 
1234-0004  | 2017-08-08 | 150 

回答

1

你可以試試下面的代碼,

void Main() 
{ 
    List<LedgerAccount> account = new List<UserQuery.LedgerAccount>() 
    { 
     new LedgerAccount() { AccountNumber = "1234-0001", BalanceDate = new DateTime(2017, 8, 8), Value = 100 }, 
     new LedgerAccount() { AccountNumber = "1234-0002", BalanceDate = new DateTime(2017, 8, 8), Value = 250 }, 
     new LedgerAccount() { AccountNumber = "1234-0003", BalanceDate = new DateTime(2017, 8, 8), Value = 500 }, 
     new LedgerAccount() { AccountNumber = "1234-0004", BalanceDate = new DateTime(2017, 8, 8), Value = 150 }, 
     new LedgerAccount() { AccountNumber = "1234-0001", BalanceDate = new DateTime(2017, 8, 9), Value = 110 }, 
     new LedgerAccount() { AccountNumber = "1234-0002", BalanceDate = new DateTime(2017, 8, 9), Value = 230 }, 
     new LedgerAccount() { AccountNumber = "1234-0003", BalanceDate = new DateTime(2017, 8, 9), Value = 400 }, 
     new LedgerAccount() { AccountNumber = "1234-0001", BalanceDate = new DateTime(2017, 8, 10), Value = 120 }, 
     new LedgerAccount() { AccountNumber = "1234-0002", BalanceDate = new DateTime(2017, 8, 10), Value = 210 }, 
    }; 

    account.GroupBy(m => m.AccountNumber).Select(m => m.OrderByDescending(s => s.BalanceDate).FirstOrDefault()).Dump(); 
} 

public class LedgerAccount 
{ 
    public string AccountNumber { get; set; } 
    public DateTime BalanceDate { get; set; } 
    public int Value { get; set; } 
} 

LINQ查詢您的要求是

var result = account.GroupBy(m => m.AccountNumber) 
     .Select(m => m.OrderByDescending(s => s.BalanceDate).FirstOrDefault()) 

輸出

AccountNumber BalanceDate    Value 
__________________________________________________ 
1234-0001  8/10/2017 12:00:00 AM  120 
1234-0002  8/10/2017 12:00:00 AM  210 
1234-0003  8/9/2017 12:00:00 AM  400 
1234-0004  8/8/2017 12:00:00 AM  150