13

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, Where or Select, can I rely on the resulting IEnumerable<Foo> to iterate in the same relative order as the original list?

verdesmarald
  • 11,646
  • 2
  • 44
  • 60
  • I won't try to answer your question directly, because @Mehrdad already did a good job of that, but if you really want to understand what Linq is doing under the covers then have a look at Jon Skeet's excellent [EduLinq series of blog posts](http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx). – Andrew Cooper May 27 '11 at 01:13
  • 1
    See also http://stackoverflow.com/questions/204505/preserving-order-with-linq – goodeye Nov 27 '12 at 22:59

1 Answers1

20

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).

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789