Linq:在集合中查找元素 [英] Linq: Find Element in a Collection
本文介绍了Linq:在集合中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为Albums
的集合,其中包含来自类Album
的对象.此类具有属性Songs
,它是Song
对象的集合.每个Song
都有一个唯一的ID.
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; }
...
}
是否可以使用Linq在专辑"专辑中找到一首歌曲?我不知道如何,对Ling还是陌生的. 我尝试了一下:
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);
非常感谢
Vincent
推荐答案
Albums.SelectMany(a=>a.Songs).FirstOrDefault(song => song.Id == id)
SelectMany将为所有专辑创建一个平坦的列表,列出所有歌曲,然后您可以选择具有适当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.
这篇关于Linq:在集合中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文