c# - LINQ-to-objects 中的 Enumerable.Where 是否保留顺序?

标签 c# .net linq linq-to-objects

<分区>

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提到此方法返回一个无序序列。

关于c# - LINQ-to-objects 中的 Enumerable.Where 是否保留顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7259560/

相关文章:

.net - 从具有不同类型的 HttpWebResponse GetResponseStream 反序列化 XML

c# - 如何在运行时获取 WPF 元素的尺寸而不在编译时指定它们

c# - 如何读取/写入特定数量的字节到文件

c# - 如何使用 ComImport?

c# - Entity Framework 4 中的简单条件 LINQ 查询

c# - 直接反/序列化到/从 XML Linq

c# - lambda 表达式中的 Where 条件 c#

c# - 为什么不使用自定义字体? Xamarin.Forms.iOS

c# - .NET/SQL Server 中的连接池?

c# - 免费的 Windows 安装程序