选择列表中的所有对象

时间:2014-03-18 14:08:39

标签: c# list

我有三个对象:

  

艺术家,专辑和曲目。

艺术家存储在List<Artist>和艺术家对象内,还有艺术家专辑的另一个列表(List<Albums>)而在相册对象中还有另一个曲目列表(List<Track>

你会如何一次选择所有曲目?

有没有办法:

TrackList.AddRange(ArtistList.Albums.Tracks);

到目前为止,我一直这样做:

foreach (Artist artist in artistlist)
  {
     if (artist.Albums != null)
     {
       ForEach(Album album in artist.Albums)
       {
         Context.AddRange(album.Tracks);
       }
     }
   }

2 个答案:

答案 0 :(得分:6)

你可以尝试

TrackList.AddRange(
  ArtistList.SelectMany(a => a.Albums)
            .SelectMany(a => a.Tracks))

或者那种效果。我在SelectMany上有点生疏,但我相信它可以在这里使用。

我也是 不确定此处是否还需要null检查。但您可以在Where之前添加SelectMany子句。

答案 1 :(得分:1)

可以使用IEnumerable<T>的{​​{3}}扩展方法完成。

相关问题