Monday, November 2, 2015

row_number() in lambda experssion

Hi friends,

Today I am going to show how row_number() implement in lambda expression.

Suppose a list of customer say List<Customer>. Customer have CustomerId, LoginDate,....

If you want to know the latest login date of each customer.


var customerLoginList = customers.OrderByDescending(x => x.LoginDate).GroupBy(x => x.CustomerId).
                           Select(g => new { g, count = g.Count() }).
                           SelectMany(t => t.g.Select(b => b).
                           Zip(Enumerable.Range(1, t.count), (j, i) => new { j.CustomerId, j.LoginDate, rn = i }));


From the above code you will get list which contains customerid with row number. Now you just filter the list where rn = 1.

No comments:

Post a Comment