2015-06-16 99 views
1

我在创建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 = ... 
        }); 
+3

让我们来看看您遇到那就麻烦查询请。这是Linq到SQL还是Linq到对象或...? TransactionDate是一个DateTime对象吗? –

回答

1

一种方式是通过startDate被过滤,通过ID分组,由date订购,并抓住该组的第一个元素:

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

这很奇妙,只能认为它应该是OrderByDescending。 – Master

+0

.Before()定义在哪里? –

+0

@StephenKennedy我没有看到OP的代码编辑,所以我提供了一种伪代码的方式来展示这个概念。感谢您的评论! – dasblinkenlight