2015-06-16 139 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