返回带有id ==的元素的rownumber的LINQ语句?

Ant*_*nte 11 c# linq-to-sql

如何编写返回带有id ==的元素的ROWNUMBER的LINQ语句?

Sco*_*vey 12

我知道没有直接的方法可以做到这一点.您必须将整个查询拉到客户端,然后您可以在行编号中进行投影.作为替代方法,您可以编写一个使用ROW_NUMBER的存储过程,然后将该proc从Linq命中到SQL.

在您的情况下,您将能够做到这一点的唯一方法是客户端.请记住,以下语句不会在服务器上执行此操作,但会下拉整个表并在客户端获取索引...

using (var dc = new DataClasses1DataContext())
{
    var result = dc.Users
        .AsEnumerable()     // select all users from the database and bring them back to the client
        .Select((user, index) => new   // project in the index
        {
            user.Username,
            index
        })
        .Where(user => user.Username == "sivey");    // filter for your specific record

    foreach (var item in result)
    {
        Console.WriteLine(string.Format("{0}:{1}", item.index, item.Username));
    }
}
Run Code Online (Sandbox Code Playgroud)