Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Enumerable.Where in LINQ-to-objects preserve order? [duplicate]

var source = new List<string> { "A1", "A2", "B1", "B2" };
var filtered = source.Where(s => s.StartsWith("A"));

foreach (var s in filtered)
    Console.WriteLine(s);    // outputs first A1 and then A2

It seems like Enumerable.Where keeps the original order of elements when used on an ordered IEnumerable (such as a List<T> or T[]). Is this always the case? If yes, where is this documented?

like image 681
Heinzi Avatar asked Aug 31 '11 15:08

Heinzi


2 Answers

Microsoft does actually document that LINQ to Objects preserves ordering. The document http://msdn.microsoft.com/en-us/library/dd460677%28v=vs.110%29.aspx says

In PLINQ, the goal is to maximize performance while maintaining correctness. A query should run as fast as possible but still produce the correct results. In some cases, correctness requires the order of the source sequence to be preserved; however, ordering can be computationally expensive. Therefore, by default, PLINQ does not preserve the order of the source sequence. In this regard, PLINQ resembles LINQ to SQL, but is unlike LINQ to Objects, which does preserve ordering.

As mentioned in this stackoverflow article microsoft documents for some LINQ methods that they do not preserve order. For example the documentation of distinct mentions that this method returns an unordered sequence.

like image 121
Stephan Seefeld Avatar answered Nov 08 '22 17:11

Stephan Seefeld


The order is preserved using the Enumerable.Where method.

There was a similar question asked on SO, and the first answer breaks down which methods preserve the order:

Preserving order with LINQ

like image 36
James Johnson Avatar answered Nov 08 '22 17:11

James Johnson