GroupBy and OrderBy Methods
Understand how to group elements in collections using LINQ's GroupBy method and how to transform and count grouped data. Discover the use of anonymous objects for grouping by multiple properties. Learn to sort collections with OrderBy and ThenBy methods, including ordering by multiple keys in ascending or descending order.
How to group elements of a collection
The GroupBy method groups the elements of a collection based on a grouping key. This method returns a collection of groups, or buckets, organized by that key.
For example, let’s group our movies by rating.
The GroupBy method receives as a parameter a delegate with a property to use as a key when grouping elements. In our previous example, we used the Rating and wrote movie => movie.Rating.
The result of GroupBy is a collection of groups or buckets. In our example, the type of the return collection was IEnumerable<IGrouping<float, Movie>>. That’s why we needed two foreach loops to print the movies in each group. One to print the ratings ...