开发者

Do LINQ's Enumerable Methods Maintain Relative Order of Elements?

Say I have List<Foo> foos where the current order of elements is important. If I then apply a LINQ Enumerable method such as GroupBy, 开发者_如何学CWhere or Select, can I rely on the resulting IEnumerable<Foo> to iterate in the same relative order as the original list?


Yes, for Enumerable methods (LINQ to Objects, which applies to List<T> you mentioned), you can rely on the order of elements returned by Select, Where, or GroupBy. This is not the case for things that are inherently unordered like ToDictionary or Distinct.

From Enumerable.GroupBy documentation:

The IGrouping<TKey, TElement> objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping<TKey, TElement>. Elements in a grouping are yielded in the order they appear in source.

This is not necessarily true for IQueryable extension methods (other LINQ providers).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜