4

How do I add ROW_NUMBER to a LINQ query or Entity?

How can I convert this solution to VB.NET?

var start = page * rowsPerPage;
Products.OrderByDescending(u => u.Sales.Count())
    .Skip(start)
    .Take(rowsPerPage)
    .AsEnumerable()
    .Select((u, index) => new { Product = u, Index = index + start }); // this line gets me

I'm having trouble porting that last line. I have been unable to locate a VB.NET example.

I'm actually not looking for any paging functionality like the example provides, just good old-fashioned Row_Number(Order By X) row index.

Community
  • 1
  • 1
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
  • What is the purpose of the OrderByDescending(u => u.Sales.Count()) in this example? Since the count doesn't change during the query, this effectively does nothing other than spin cycles (assuming SQL doesn't optimize it out of the execution plan). – Jim Wooley Sep 01 '11 at 14:26
  • I don't know. This is a code snippet from another Stackoverflow post. I'm interested in projecting a row index into the list of anon objects in VB.NET – Brian Webster Sep 01 '11 at 15:43
  • In that case, use the overload in Select David B mentioned below. – Jim Wooley Sep 01 '11 at 17:18

1 Answers1

6

LinqToSql can't do a Row_Number(Order By X) in the database.

The c# code you posted does it against in-memory instances by calling Enumerable.Select

On the msdn page for Enumerable.Select, there's a vb.net example.


Here is a working example that demonstrates the projection of a row index in VB.NET:

Dim R = (
     From P In DB.Products Select P
  ).AsEnumerable().Select(
     Function(Product, index) New With {index, Product}
  )

Response.Write(R(12).Product.Doc_width.ToString()) 'Access object members
Response.Write(R(12).index.ToString() 'Access Row Index
Tom Halladay
  • 5,651
  • 6
  • 46
  • 65
Amy B
  • 108,202
  • 21
  • 135
  • 185