List search from within

Viewed 50

I have an object which has a list of other objects which has a list of yet another object. My favorite example:

public class Artist
{
    int ArtistID;
    string ArtistName;
    List<Album> Albums;
}
public class Album
{
    int AlbumID;
    string AlbumName
    List<Song> Songs
}
public class Song
{
    int SongID;
    string SongName;
}

Since a song can be covered by many artists, I want to search for all artists that recorded a specific song. I know this can be done using iteration, but I'm sure there's way to do it in a single statement.

List<Artist> list = all artists that sang "Yesterday"

Thank you.

3 Answers

Assuming a list of Artist called artists you're looking for

var yesterdaySingers = artists.Where(
       art => art.Albums.Any(
               alb => alb.Songs.Any(song => song.SongName == "Yesterday")
       )
).ToList();

Note you must add using System.Linq; to use the above.

You can accomplish this using lambda statements.

var artists = artistList
   .Where(art => art.Albums.Any(alb => alb.Songs.Any(song => song.SongName == "Yesterday")))
   .ToList();

I fear your data/class structure is inherently faulty.

Since a song can be covered by many artists, I want to search for all artists that recorded a specific song. I know this can be done using iteration, but I'm sure there's way to do it in a single statement.

"Each artist can have multiple songs, and each song can have multiple aritsts", sounds like the book example of the many-to-many relationship. However, what you have is two layers of 1:N.

You should change it so Song and Artist are in a proper N:M relationship, using a connection table.

Related