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


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


3498
2017-07-15 16:58


起源



答案:


我知道没有直接的方法可以做到这一点。您必须将整个查询拉到客户端,然后您可以在行编号中进行投影。作为替代方案,您可以编写一个使用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));
    }
}

12
2017-07-15 17:09



谢谢,斯科特。所以我猜你会ToList()它,然后是IndexOf()? - Robert Harvey♦
当然,我还添加了一个示例,说明如何使用Select的重载来为您提供索引。 - Scott Ivey
甜。得到我的upvote。 - Robert Harvey♦
我试图想出一个解决方案 .TakeWhile(xxx).Count(),但它也无法转换为Sql,并且当记录根本不存在时可能会有不良/不正确的结果。 - Ryan Versaw
dc.Pictures .Select(p => p.IsBest).AsEnumerable().Select((p,i)=> new {p.PictureID,i})。Where(p => p.PictureID = id);我不是linq的那个上帝,我不知道为什么但p.PictureID无法访问。你能告诉我为什么吗? - Ante


答案:


我知道没有直接的方法可以做到这一点。您必须将整个查询拉到客户端,然后您可以在行编号中进行投影。作为替代方案,您可以编写一个使用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));
    }
}

12
2017-07-15 17:09



谢谢,斯科特。所以我猜你会ToList()它,然后是IndexOf()? - Robert Harvey♦
当然,我还添加了一个示例,说明如何使用Select的重载来为您提供索引。 - Scott Ivey
甜。得到我的upvote。 - Robert Harvey♦
我试图想出一个解决方案 .TakeWhile(xxx).Count(),但它也无法转换为Sql,并且当记录根本不存在时可能会有不良/不正确的结果。 - Ryan Versaw
dc.Pictures .Select(p => p.IsBest).AsEnumerable().Select((p,i)=> new {p.PictureID,i})。Where(p => p.PictureID = id);我不是linq的那个上帝,我不知道为什么但p.PictureID无法访问。你能告诉我为什么吗? - Ante


您应该能够使用Skip和Take扩展方法来完成此任务。

例如,如果您想要第10行:

from c in customers
           where c.Region == "somewhere"
           orderby c.CustomerName
           select new {c.CustomerID, c.CustomerName} 
           .Skip(9).Take(1);

3
2017-07-15 17:05



我不认为这是被问到的问题的答案,但它得到了投票,所以我把它留在这里。 - Robert Harvey♦


如何将行号投影到Linq查询结果中
如何将行号投影到Linq查询结果中


1



Linq to SQL中不支持Select的重载。将抛出NotSupportedException()。 - Scott Ivey