我有几个这样的课程:
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;}
}
我有一个TvShows列表,我希望以有效的方式获得所有TvShows所有季节的总集数。显然有一些foreach解决方案:
int count = 0;
foreach (var show in tvShows) {
foreach (var season in show.Seasons {
foreach (var episode in season.Episodes {
count++;
}
}
}
我能用linq做什么更优雅或更快?
答案 0 :(得分:3)
嗯,您的代码相当于:
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);
我希望最后一次效率最高 - 但实际上,除非你有很多节目,否则我希望所有的选择都非常快。最后也很优雅,所以这就是我想要的。
答案 1 :(得分:2)
像
这样的东西tvShows.SelectMany(show => show.Seasons)
.Sum(season => season.Episodes.Count)