使用LINQ其中的项目列表包含组件列表中的任何组件
问题描述:
使用LINQ,如何找到组件列表包含来自另一组件列表的组件列表的项目列表?使用LINQ其中的项目列表包含组件列表中的任何组件
结构:
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。
我试过如下:
items
.Select(i => i.Components)
.Where(c => components.Contains(c.Any(x => x.Name.ToString()));
我收到以下错误:
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
列表。
也不要使用Select
,如果你想获得Item
回列表:
var result = items.Where(i => i.Components.Any(c => components.Contains(c.Name)));
答
,因为Any
预计布尔值,但将返回字符串:x.Name.ToString
。
你可以在你的情况下检查两个序列的交集:
items.Where(x => x.Components.Intersect(components).Any())
Intersect
将返回非空序列,如果两个item.Components
和components
包含相同的元素。如果序列不是空的,则不带参数的Any
将返回true
。