elegant and efficient linq solultion to count number of episodes

I have several classes like this:

public class TvShow
{
    public Title {get; set;}
    public List<Season> Seasons {get; set;}
}

public class Season
{
    public int SeasonNumber {get; set;}
    public List<Episode> Episodes {get; set;}
}

public class Episode
{
    public int EpisodeNumber {get; set;}
}

I have a list of TvShows, I want to get the total episode count over all seasons of all TvShows in an efficient manner. Obviously there is the foreach solutions:

int count = 0;
foreach (var show in tvShows) {
    foreach (var season in show.Seasons {
        foreach (var episode in season.Episodes {
            count++;
        }
    }
}

anything more elegant or faster I can do with linq?

Jon Skeet
people
quotationmark

Well, your code is equivalent to:

int count = tvShows.SelectMany(show => show.Seasons)
                   .SelectMany(season => season.Episodes)
                   .Count();

Or you could use Sum to find out how many episodes are in each show, and then again to find out the total number of episodes across all shows:

int count = tvShows.Sum(show => show.Seasons.Sum(season => season.Episodes.Count));

Or a sort of mixture, just summing the episode count of all seasons in all shows:

int count = tvShows.SelectMany(show => show.Seasons)
                   .Sum(season => season.Episodes.Count);

I'd expect the last to be the most efficient - but really, unless you've got an awful lot of shows, I'd expect all options to be very fast. The last is also pretty elegant though, so that's what I'd go for.

people

See more on this question at Stackoverflow