Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Objects: does GroupBy preserve order of elements?

People also ask

Does ToList preserve order?

The simple answer is no, ToList will just loop over the source enumerable and keep the same order.

What does Groupby do in Linq?

In LINQ, grouping operators pick the elements of the sequence or collection which contains common attributes and serve them in a group. Or in other words, we can say that the grouping operator returns the group of elements based on the given key.

Does IEnumerable guarantee order?

IEnumerable/IEnumerable<T> makes no guarantees about ordering, but the implementations that use IEnumerable/IEnumerable<T> may or may not guarantee ordering.


Found answer on MSDN: Yes.

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.