Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is LINQ extension method Where guaranteed to preserve order?

Tags:

c#

linq

If I have a list of messages in a publish/subscribe architecture, I assume it is reasonable to use IEnumerable.Where on an underlying List to retrieve particular messages and trust the order of the messages?

like image 712
LinusK Avatar asked Oct 04 '11 20:10

LinusK


2 Answers

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.

like image 137
Steven Avatar answered Sep 29 '22 19:09

Steven


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.

like image 26
BrokenGlass Avatar answered Sep 29 '22 20:09

BrokenGlass