我有几个这样的类:
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;}
}
我有一个电视节目列表,我想以一种有效的方式获得所有电视节目所有季节的总集数。显然有两个解决方案:
int count = 0;
foreach (var show in tvShows) {
foreach (var season in show.Seasons {
foreach (var episode in season.Episodes {
count++;
}
}
}
我可以用linq做什么更优雅或更快的事情吗? 好吧,你的代码相当于:
int count = tvShows.SelectMany(show => show.Seasons)
.SelectMany(season => season.Episodes)
.Count();
或者你可以使用Sum
找出每个节目有多少集,然后再找出所有节目的总集数:
int count = tvShows.Sum(show => show.Seasons.Sum(season => season.Episodes.Count));
或者是一种混合,只是把所有剧集的所有季节的剧集数加起来:
int count = tvShows.SelectMany(show => show.Seasons)
.Sum(season => season.Episodes.Count);
我希望最后一个是最有效的,但实际上,除非你有很多节目,我希望所有的选择都非常快。最后一个也很优雅,所以这就是我想要的
类似
tvShows.SelectMany(show => show.Seasons)
.Sum(season => season.Episodes.Count)