开发者

Is LINQ extension method Where guaranteed to preserve order?

开发者 https://www.devze.com 2023-04-10 10:36 出处:网络
If I have a list of messages in a publish/subscribe architecture, I assume it is reasonable to use IEnumerable.Where on an unde开发者_开发技巧rlying List to retrieve particular messages and trust the

If I have a list of messages in a publish/subscribe architecture, I assume it is reasonable to use IEnumerable.Where on an unde开发者_开发技巧rlying List to retrieve particular messages and trust the order of the messages?


The Enumerable.Where extension method will, but the Queryable.Where extension method won't.

Enumerable.Where has to preserve the order, since it streams the results and there is no cache (and no logic in caching results).

Queryable.Where, on the other hand, translates the given call to something the underlying data source will understand and there is no guarantee about the ordering what so ever. This effect can be observed easily when working with relational databases. The addition of a where clause can let the database pick another index, which can change the ordering of the results. Without an explicit order by clause, the selected index will typically determine the ordering of the results.


For Linq to Objects / IEnumerable this is true - order will be maintained - for IQueryable providers it depends on the provider, many providers do not maintain order.

It looks like this fact (maintaining order) is not documented on MSDN though, so I would consider it an implementation detail that - although unlikely - might change in the future.

0

精彩评论

暂无评论...
验证码 换一张
取 消