可能的 linq 错误/问题
今天,我遇到了 LINQ 查询的问题,经过一些调试后,我能够解决该问题,但对我来说,这似乎是 LINQ 工作方式中的一个错误。这是我所拥有的:
var myitem = context
.items
.OrderByDescending(x => x.DateEdited)
.FirstOrDefault(x => x.fkId == myFkId && x.DateEdited < someDate);
在我的数据库中,我有一个包含一些记录的表,我想检索早于“someDate”并且在列中具有特定外键的最新记录。然而上面的查询不起作用。它返回带有匹配外键的最旧记录。我最终不得不像这样重写我的查询才能使其正常工作:
var myitem = context
.items
.Where(x => x.fkId == myFkId && x.DateEdited < someDate)
.OrderByDescending(x => x.DateEdited)
.FirstOrDefault();
在调试中,我发现“x.DateEdited < someDate”正在对 IEnumerable 重新排序,因此我最终不得不将 OrderByDescending 子句放在日期检查。
还有其他人遇到过这个问题吗?这是一个错误还是预期的功能?
I was having an issue with a LINQ query today and after some debugging I was able to resolve the issue but it seems like a bug to me in the way LINQ works. Here is what I had:
var myitem = context
.items
.OrderByDescending(x => x.DateEdited)
.FirstOrDefault(x => x.fkId == myFkId && x.DateEdited < someDate);
In my database I have a table with some records and I want to retrieve the most recent record that is older than "someDate" and who has a particular foreign key in a column. The above query did not work however. It was returning the oldest record with the matching foreign key. I ended up having to rewrite my query like this to get it to work:
var myitem = context
.items
.Where(x => x.fkId == myFkId && x.DateEdited < someDate)
.OrderByDescending(x => x.DateEdited)
.FirstOrDefault();
In my debugging I found out that the "x.DateEdited < someDate" was re-ordering the IEnumerable so I ended up having to put my OrderByDescending clause after the date check.
Has anybody else run into this issue? Is it a bug or expected functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管
.OrderByDescending()
返回IOrderedEnumerable
,但.FirstOrDefault()
是 .Where()
的快捷方式> 只返回一个IEnumerable
,不保证顺序。基本上,添加过滤器并不能保证数据的顺序。如果您从头开始查看生成的 SQL,您将从 orderby 中获得一个嵌套的子结果,然后再次对其进行过滤。
Even though
.OrderByDescending()
returns anIOrderedEnumerable
, the.FirstOrDefault()
is a shortcut to .Where()
which only returns anIEnumerable
which does not guarantee order.Basically, adding a filter does not guarantee the order of the data. If you look at the generated SQL from the first, you will get a nested subresult from the orderby that is then filtered again.
通常,如果某个操作没有显式定义输出顺序,则在您自己指定/应用它之前,您不能依赖于任何特定顺序的结果。
除非您知道对中间结果进行排序会在算法的下一步中提高性能,否则没有理由这样做。只需将订购作为最后的处理步骤即可。
Generally, if an operation does not explicitly define the output order, you can't depend on the result being in any particular order until you specify/apply it yourself.
Unless you know that ordering an intermediate result will yield performance improvements in the next step of an algorithm, there's no reason to so. Just apply the ordering as a final processing step.