Select all objects in a list

5.4k views Asked by At

I have three objects:

Artist, Albums and Track.

The artists are stored in a List<Artist> and inside the Artist object there's another list for the artist's Albums (List<Albums>) And in the Album object there is yet another list for the tracks (List<Track>)

How would you go about selecting all the tracks at once?

Is there any way to do:

TrackList.AddRange(ArtistList.Albums.Tracks);

Until now I have been doing this:

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

There are 2 answers

3
Joey On BEST ANSWER

You could try

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

Or something to that effect. I'm a little rusty on SelectMany, but I'm fairly confident it can be used here.

I'm also not sure whether your null check is needed here, too. But you can add a Where clause before the SelectMany.

0
Codor On

It could be done with the SelectMany extension method of IEnumerable<T>.