Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, May 27, 2016

Linq: Find Element in a Collection

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 Albums    public class Album  {      ...      public virtual ICollection 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

Answer by simonlchilds for Linq: Find Element in a Collection


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);  

Answer by Darren Lewis for Linq: Find Element in a Collection


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.

Answer by Fischermaen for Linq: Find Element in a Collection


My suggestion to find an ablum with a certain song:

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

Answer by Falanwe for Linq: Find Element in a Collection


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);   

Answer by Mike Cowan for Linq: Find Element in a Collection


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


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.