LINQ到对象中的Enumerable.Where是否保留顺序? [英] Does Enumerable.Where in LINQ-to-objects preserve order?

查看:183
本文介绍了LINQ到对象中的Enumerable.Where是否保留顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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[])上使用时,将保留元素的原始顺序.总是这样吗?如果是,请在哪里记录?

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确实记录了LINQ to Objects保留顺序的事实.文件 http://msdn.microsoft.com/zh-cn/library/dd460677%28v = vs.110%29.aspx

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

在PLINQ中,目标是在保持性能的同时最大化性能 正确性.查询应尽可能快地运行,但仍会产生 正确的结果.在某些情况下,正确性要求的顺序为 要保留的源序列;但是,订购可以是 计算上昂贵.因此,默认情况下,PLINQ不 保留源序列的顺序.对此,PLINQ 与LINQ to SQL类似,但与 LINQ to Objects不同, 保留顺序.

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.

此stackoverflow文章微软文档中所述,它们未保留某些LINQ方法命令.例如,文档的不同提到此方法返回无序序列.

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.

这篇关于LINQ到对象中的Enumerable.Where是否保留顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆