Linq: find an item in the collection

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

 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's collection? I have no idea how, I'm new to Ling. I tried a little:

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

Many thanks,

Vincent

+6
source share
5 answers
 Albums.SelectMany(a=>a.Songs).FirstOrDefault(song => song.Id == id) 

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

+12
source

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 do not ...

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

If you want to return an album containing a song with the given identifier, you should use the following query:

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

if you want to get a song:

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

My suggestion is to find an ablum with a specific song:

 Album albumFound = Albums.FirstOrDefault(item => item.Songs.FirstOrDefault(song => song.Id == id) != null); 
0
source
 var query = from album in Albums from song in album.Songs where song.Id == id; var song = query.FirstOrDefault(); 
0
source

Source: https://habr.com/ru/post/901099/


All Articles