如何编写返回带有id ==的元素的ROWNUMBER的LINQ语句?
如何编写返回带有id ==的元素的ROWNUMBER的LINQ语句?
我知道没有直接的方法可以做到这一点。您必须将整个查询拉到客户端,然后您可以在行编号中进行投影。作为替代方案,您可以编写一个使用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));
}
}
我知道没有直接的方法可以做到这一点。您必须将整个查询拉到客户端,然后您可以在行编号中进行投影。作为替代方案,您可以编写一个使用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));
}
}
您应该能够使用Skip和Take扩展方法来完成此任务。
例如,如果您想要第10行:
from c in customers
where c.Region == "somewhere"
orderby c.CustomerName
select new {c.CustomerID, c.CustomerName}
.Skip(9).Take(1);
如何将行号投影到Linq查询结果中
如何将行号投影到Linq查询结果中