LINQ 中的行号
我有一个像这样的 linq 查询:
var accounts =
from account in context.Accounts
from guranteer in account.Gurantors
where guranteer.GuarantorRegistryId == guranteerRegistryId
select new AccountsReport
{
recordIndex = ?
CreditRegistryId = account.CreditRegistryId,
AccountNumber = account.AccountNo,
}
我想用 LINQ 返回的集合中当前行号的值填充 recordIndex。我怎样才能得到行号?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
linq-to-entities 不支持行号。您必须首先从数据库中检索没有行号的记录,然后通过 linq-to-objects 添加行号。像这样的东西:
Row number is not supported in linq-to-entities. You must first retrieve records from database without row number and then add row number by linq-to-objects. Something like:
LINQ to object 具有适用于任何枚举器的内置功能:
http://weblogs.asp.net/fmarguerie/archive/2008/11/10/using-the-select-linq-query-operator-with-indexes.aspx
编辑:虽然 IQueryable 也支持它(此处和此处)有人提到,这不幸的是不适用于 LINQ to SQL/Entities。
将导致:
还有其他 LINQ 扩展方法(例如 < code>.Where) 带有额外的索引参数重载
LINQ to objects has this builtin for any enumerator:
http://weblogs.asp.net/fmarguerie/archive/2008/11/10/using-the-select-linq-query-operator-with-indexes.aspx
Edit: Although IQueryable supports it too (here and here) it has been mentioned that this does unfortunately not work for LINQ to SQL/Entities.
Will result in:
There are other LINQ Extension methods (like
.Where
) with the extra index parameter overload尝试像这样使用 let:
我现在无法使用实际的 LINQ to SQL 或实体框架来测试它。请注意,上面的代码将在多次执行查询之间保留计数器的值。
如果您的特定提供商不支持此功能,您始终可以 foreach (从而强制执行查询)并在代码中手动分配号码。
Try using let like this:
I cannot test it with actual LINQ to SQL or Entity Framework right now. Note that the above code will retain the value of the counter between multiple executions of the query.
If this is not supported with your specific provider you can always foreach (thus forcing the execution of the query) and assign the number manually in code.
因为问题中的查询按单个 id 进行过滤,所以我认为给出的答案不会有帮助。当然,您可以在内存客户端完成这一切,但是根据数据集的大小以及是否涉及网络,这可能是一个问题。
如果您需要 SQL
ROW_NUMBER [..] OVER [..]
等效项,我知道的唯一方法是在 SQL Server 中创建一个视图并对其进行查询。Because the query inside the question filters by a single id, I think the answers given wont help out. Ofcourse you can do it all in memory client side, but depending how large the dataset is, and whether network is involved, this could be an issue.
If you need a SQL
ROW_NUMBER [..] OVER [..]
equivalent, the only way I know is to create a view in your SQL server and query against that.经过测试并且有效:
按如下方式修改您的代码:
希望这有帮助..虽然已经晚了:)
This Tested and Works:
Amend your code as follows:
Hope this helps.. Though its late:)