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
它似乎像 Enumerable.Where
在有序的 IEnumerable(例如 List<T>
或 T[]
)上使用时,保持元素的原始顺序。总是这样吗?如果是,记录在哪里?
Microsoft 确实记录了 LINQ to Objects 保留顺序。文档
http://msdn.microsoft.com/en-us/library/dd460677%28v=vs.110%29.aspx说
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.
如 this stackoverflow article 中所述某些 LINQ 方法的 Microsoft 文档指出它们不保留顺序。例如 documentation of distinct提到此方法返回一个无序序列。