Linq:在集合中查找元素 [英] Linq: Find Element in a Collection

查看:173
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆