开发者

Is LINQ extension method Where guaranteed to preserve order?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜