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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With