views:

59

answers:

3

I simply want to include a row number against the returned results of my query.

I found the following post that describes what I am trying to achieve but gives me an exception

http://vaultofthoughts.net/LINQRowNumberColumn.aspx

"An expression tree may not contain an assignment operator"

In MS SQL I would just use the ROWNUMBER() function, I'm simply looking for the equivalent in LINQ.

A: 

LINQ to SQL allows you to map a SQL function. While I've not tested this, I think this construct will work:

public partial class YourDataContext : DatContext
{
    [Function(Name = "ROWNUMBER")]
    public int RowNumber()
    {
        throw InvalidOperationException("Not called directly.");
    }
}

And write a query as follows:

from author in db.Authors
select new { Lp = db.RowNumber(), Name = author.Name };
Steven
+2  A: 

Use AsEnumerable() to evaluate the final part of your query on the client, and in that final part add a counter column:

int rowNo = 0;
var results = (from data in db.Data
               // Add any processing to be performed server side
               select data)
              .AsEnumerable()
              .Select(d => new { Data = d, Count = ++rowNo });
Richard
+1  A: 

I'm not sure whether LINQ to SQL supports it (but it propably will), but there's an overload to the Queryable.Select method that accepts an lambda with an indexer. You can write your query as follows:

db.Authors.Select((author, index) => new
{
    Lp = index, Name = author.Name
});

UPDATE:

I ran a few tests, but unfortunately LINQ to SQL does not support this overload (both 3.5sp1 and 4.0). It throws a NotSupportedException with the message:

Unsupported overload used for query operator 'Select'.

Steven
-1: There is no `Queryable.Select` which passes an index to the delegate.
Richard
@Richard: Did you even bother to check this? Here is the overload I talked about: http://msdn.microsoft.com/en-us/library/bb534638.aspx. Please reevaluate your negative vote.
Steven
@Steven: I had seen confirmation (but I can't find where now -- of course): ORMs typically don't implement it. See also http://stackoverflow.com/questions/1873850/which-orm-tools-support-this-version-of-queryable-select-extension-method/1905527
Richard
@Richard: I've did a little test, and you're right. Unfortunately, L2S does not support this (both 3.5 and 4.0). I thought of removing my answer, but perhaps this information and our discussion is still of some use to someone.
Steven
@Steven: Removed the -1, with the caveat that some LINQ providers (L2S being significant here) don't support this.
Richard