使用LINQ,其中项目列表包含组件列表中的任何组件 [英] Use LINQ where list of items contains any component in a list of components

查看:47
本文介绍了使用LINQ,其中项目列表包含组件列表中的任何组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ,如何从另一个组件列表中的组件列表中找到包含组件的项目列表?

Using LINQ, how can I find a list of items where it's list of components contains a component from another list of components?

结构:

class Item
{
    public List<Component> Components {get;set;}
}

class Component
{
    public string Name {get;set;}
}

示例:

var components = new List<string> { "C1", "C2" , "C3" }
var items = new List<Item>
{
    new Item("IT1")
    {
        Components = new List<Component> { "C1", "C4","C5" }                    
    },
    new Item("IT2")
    {
        Components = new List<Component> { "C6", "C7","C8" }
    },
    new Item("IT3")
    {
        Components = new List<Component> { "C2", "C0","C9" }
    }
} 

输出将返回项目IT1和IT3.

The output will returns items IT1 and IT3.

我尝试了以下操作:

items
    .Select(i => i.Components)
    .Where(c => components.Contains(c.Any(x => x.Name.ToString()));

我遇到以下错误:

无法将lambda表达式转换为预期的委托类型,因为 块中的某些返回类型不是隐式可转换的 委托返回类型

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

推荐答案

应该是相反的方式:首先是Any,然后是Contains.您希望在components列表中获取所有任何个组件中包含 的项目.

It should be the other way around: first the Any and then the Contains. You would like to get all items that have any of there components contained in the components list.

如果您想获取Item的列表,也不要使用Select:

Also don't use the Select if you'd like to get a list of Item back:

var result = items.Where(i => i.Components.Any(c => components.Contains(c.Name)));

这篇关于使用LINQ,其中项目列表包含组件列表中的任何组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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