Here lists a payment history of a customer in a db table
CustomerId PayId FeePaid
xx-yy-zz 37 0
xx-yy-zz 32 0
xx-yy-zz 31 30.00
xx-yy-zz 28 0
xx-yy-zz 26 0
xx-yy-zz 18 35.99
xx-yy-zz 17 0
xx-yy-zz 16 0
xx-yy-zz 9 12.00
xx-yy-zz 6 0
The PaymentId column is auto incremented.
How to get the last payment of this customer, i.e., the number $30.00?
My project is Asp.net API, so I need use LINQ to get the number.
3
Answers
If we assume that we’re ignoring zeros, and that
PayId
is monotonically incrementing, then presumably:as LINQ:
or as SQL:
Try this linq expression:
You wrote:
My advice would be to group the
PaymentHistories
per user, so by common value of CustomerId.Then for each group, keep the
PaymentHistory
that has the highest value ofPaymentId
. After all:PaymentId
is auto-increments, so thePaymentHistory
in the group ofPaymentHistories
of Customer X is the one with the highest PaymentIdFor this I used the overload of Queryable.GroupBy that has a parameter resultSelector, so I can precisely specify what I want in my result.
If you don’t want FeePaid, but also the PaymentId, use the following resultSelector: