linq - 如何从列表中选择具有与另一个列表中的项目匹配的属性的对象?

标签 linq list windows-phone-7

这个问题也许很难理解,但让我解释一下。我有一个ListChannel - 对象,所有对象都有 ChannelId属性(property)( int )。我也有一个不同的List ( int ) - SelectedChannelIds ,包含 ChannelId 的子集-s。

我想选择(通过LINQ?)所有Channel -具有 ChannelId 的对象-第二个匹配一个的属性 List .

换句话说,我有以下结构:

public class Lists
{
    public List<Channel> AllChannels = ChannelController.GetAllChannels();
    public List<int> SelectedChannelIds = ChannelController.GetSelectedChannels();

    public List<Channel> SelectedChannels; // = ?????
}

public class Channel
{
    // ...
    public int ChannelId { get; set; }
    // ...
}

关于 LINQ 查询的外观有什么想法吗?或者有更有效的方法吗?我正在为 Windows Phone 7 编写代码,仅供引用。

最佳答案

您可以使用 List.Contains Where子句:

public Lists()
{
    SelectedChannels = AllChannels
        .Where(channel => SelectedChannelIds.Contains(channel.ChannelId))
        .ToList();
}

请注意,如果您使用HashSet<int>,效率会更高。而不是List<int>对于SelectedChannelIds 。更改为 HashSet会将性能从 O(n2) 提高到 O(n),但如果您的列表总是很小,这可能不是一个重大问题。

关于linq - 如何从列表中选择具有与另一个列表中的项目匹配的属性的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209674/

相关文章:

python - 如何使用 Python 中的索引从列表中提取元素?

c# - 将 CommandParameter 设置为 ListBox 上当前点击的项目 (WP7)

silverlight - 在 WP7 中设置整个背景图像/颜色

c# - 如何在 C# linq 中制作 AND 运算符?

c# - 在 nhibernate 中 Linq-ing 计算属性无法解析属性错误

sql-server - Entity Framework Core 3.1.1 查询无法翻译的地方。要么以可翻译的形式重写查询,

MYSQL 获取当前星期几在列表中的项目

c# - 当没有要求和的内容时,Linq .Sum() 函数失败

java - 如何创建 DRYer 构造函数

c# - Windows Phone 7 - 验证推送通知的步骤