Linq: Find Element in a Collection

I have a collection called Albums with objects from the class Album. This class has a property Songs, which is a collection of Song objects. Each Song has an unique Id.

public IQueryable<Album> Albums

public class Album
{
    ...
    public virtual ICollection<Song> Songs { get; set; }
    ...
}

public class Song
{
    public int Id { get; set; }
    ...
}

Is it possible, using Linq, to find a Song in the Album collection? I have no idea how, I am new to Ling.
I tried a bit:

Albums.FirstOrDefault(a => a.Songs.Id == id);

Thanks a lot,

Vincent

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Albums.SelectMany(a=>a.Songs).FirstOrDefault(song => song.Id == id)

The SelectMany will create a flattened list of all songs for all albums allowing you to then select the first with the appropriate id.

Method 2

If you want to return the album that contains the song with a given Id, you should use the following query:

Albums.FirsOrDefault(a => a.Songs.Any(s => s.Id == Id));

if you want to get the song:

Albums.SelectMany(a=>a.Songs).FirstOrDefault(s => s.Id == Id);

Method 3

You need to do this if you have an album…

var album = GetAlbum();
var song = album.Songs.FirstOrDefault(s => s.ID == id);

Or this if you don’t…

var song = albumsCollection.SelectMany(s => s.Songs).FirstOrDefault(s => s.ID == id);

Method 4

My suggestion to find an ablum with a certain song:

Album albumFound = Albums.FirstOrDefault(item => item.Songs.FirstOrDefault(song => song.Id == id) != null);

Method 5

var query = from album in Albums
            from song in album.Songs
            where song.Id == id;

var song = query.FirstOrDefault();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x