Search⌘ K

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.

C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace MovieCatalog
{
internal class Program
{
public static void Main(string[] args)
{
var movies = new List<Movie>
{
new Movie("Titanic", 1998, 4.5f),
new Movie("The Fifth Element", 1997, 4.6f),
new Movie("Terminator 2", 1991, 4.7f),
new Movie("Avatar", 2009, 5),
new Movie("Platoon", 1986, 4),
new Movie("My Neighbor Totoro", 1988, 5)
};
var groupedByRating = movies.GroupBy(movie => movie.Rating);
foreach (var group in groupedByRating)
{
Console.WriteLine($"Rating: {group.Key}");
foreach (var movie in group)
{
Console.WriteLine($"{movie.Name}");
}
Console.WriteLine();
}
}
}
internal class Movie
{
public Movie(string name, int releaseYear, float rating)
{
Name = name;
ReleaseYear = releaseYear;
Rating = rating;
}
public string Name { get; set; }
public int ReleaseYear { get; set; }
public float Rating { get; set; }
}
}

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