Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Find Element in a Collection

Tags:

c#

asp.net

linq

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

like image 387
Vinzcent Avatar asked Nov 09 '11 09:11

Vinzcent


Video Answer


1 Answers

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.

like image 77
Darren Lewis Avatar answered Sep 21 '22 06:09

Darren Lewis