Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .GroupBy() guarantee order in its groupings?

Say I have an (ordered) sequence of animals:

 Eagle Elephant Tarantula Terrapin Tiger 

and I group by first letter:

Animals.GroupBy(animal => animal.First()) 

will the elements of the IGroupings in the resulting sequence be in the same order as the input sequence?

like image 348
spender Avatar asked Sep 11 '12 21:09

spender


People also ask

Does GROUP BY maintain order?

Groupby preserves the order of rows within each group. When calling apply, add group keys to index to identify pieces. Reduce the dimensionality of the return type if possible, otherwise return a consistent type.

Does order matter in GROUP BY?

No, the order doesn't matter for the GROUP BY clause. MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.

Does Linq GROUP BY preserve order?

Found answer on MSDN: Yes.

Does GROUP BY sort values?

Sort Values in Descending Order with GroupbyYou can sort values in descending order by using ascending=False param to sort_values() method. The head() function is used to get the first n rows. It is useful for quickly testing if your object has the right type of data in it.


2 Answers

Yes, they will be: GroupBy (MSDN).

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.

like image 103
McGarnagle Avatar answered Sep 21 '22 21:09

McGarnagle


Quote from the MSDN page for GroupBy:

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.

So your example will result in:

  1. Group 1

    • Eagle
    • Elephant
  2. Group 2

    • Tarantula
    • Terrapin
    • Tiger

Of course that only applies to the IEnumerable<T> implementation. The IQueryable<T> implementation has no such guarantee.

like image 40
Servy Avatar answered Sep 21 '22 21:09

Servy