What is the best way to add ROW NUMBER to a LINQ query or Entity?

asp.net entity-framework linq

Question

This simple data issue has me baffled.

I have a database of goods and I'm using the Entity framework. These goods are shown in paginated order on my results page. My results are currently sorted by how many of each product's sales there were, so my code looks like this:

return Products.OrderByDescending(u => u.Sales.Count());

This produces a dataset of my entities called IQueryable that is sorted by the quantity of sales.

I want for my results page to display each product's ranking (in the dataset). My findings need to appear as follows:

Page #1
1. Bananas
2. Apples
3. Coffee

Page #2
4. Cookies
5. Ice Cream
6. Lettuce

I'm assuming I only need to add a column to my results datatable using the SQL ROW NUMBER variable, but I'm not sure how to accomplish it.

My last page does include a foreach loop, but because I'm using a paginated collection, I don't think it would be the best idea to use that number to simulate a ranking number.

Therefore, in this scenario, how can I add a ROW NUMBER field to my query results?

1
24
7/22/2009 12:49:30 PM

Popular Answer

Implement the Indexed Select overload:

var start = page * rowsPerPage;
Products.OrderByDescending(u => u.Sales.Count())
    .Skip(start)
    .Take(rowsPerPage)
    .AsEnumerable()
    .Select((u, index) => new { Product = u, Index = index + start });
33
6/24/2010 2:16:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow