[英]Use LINQ where list of items contains any component in a list of components
使用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()));
我收到以下錯誤:
無法將lambda表達式轉換為預期的委托類型,因為該塊中的某些返回類型不能隱式轉換為委托返回類型
它應該是相反的方式:首先是Any
,然后是Contains
。 您希望獲得所有包含 components
列表中包含 任何組件的項目。
如果您想找回Item
列表,也不要使用“ Select
:
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())
如果item.Components
和components
包含相同的元素,則Intersect
將返回非空序列。 如果序列為非空,則不帶參數的Any
將返回true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.