抓取最近的交易/记录

时间:2015-06-16 16:35:32

标签: c# linq

我在创建一个linq语句时遇到问题,该语句会抓取指定startdate之前发生的最新事务。想知道是否有人可以帮助我。

例如startdate是1月20日。

Id    LoanId    TransactionDate    InterestDate    Balance
1        5         January 5        January 3        5000
1        5         January 30       January 5        10000
2        5         January 22       January 22       4000
3        6         January 3        January 1        2000

我应该在下面有一个列表

Id    LoanId    TransactionDate    InterestDate    Balance
1        5         January 5        January 3        5000
3        6         January 3        January 1        2000

我无法分组并抓住正确的值。

var transactions =  ctx.Transactions.Where(x => x.Date <= startDate)
                    .GroupBy(x => x.LoanId)
                    .Select(x => new TransactionDTO
                    {
                        LoanId = ...
                        TransactionDate = ...
                        InterestDate = ....
                        Balance = ...
                    });

1 个答案:

答案 0 :(得分:1)

一种方法是按startDate过滤,按ID分组,按date排序,然后抓取组的第一个元素:

var res = tx
    .Where(tx => tx.TransactionDate <= startDate)
    .GroupBy(tx => tx.Id)
    .Select(g => g.OrderBy(tx => tx.Date).First());