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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1132618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:59:16  来源:igfitidea点击:

LINQ statement that returns rownumber of element with id == something?

c#linq-to-sql

提问by Ante

How to write LINQ statement that returns ROWNUMBER of element with id == something?

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

采纳答案by Scott Ivey

There is no direct way to do this that I'm aware of. You'd have to pull the whole query down to the client, and the from there you could project in the row numbers. As an alternative, you could write a stored procedure that uses ROW_NUMBER, and then hit that proc from Linq to SQL.

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

In your case, the only way you're going to be able to do this would be client side. Keep in mind that the following statement is NOT going to do this at the server, but will pull down your whole table and get the index at the client...

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

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));
    }
}

回答by Robert Harvey

You should be able to use the Skip and Take extension methods to accomplish this.

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

For example, if you want row 10:

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

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

回答by Robert Harvey

How To Project a Line Number Into Linq Query Results
How To Project a Line Number Into Linq Query Results

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