簡體   English   中英

使用LINQ,其中項目列表包含組件列表中的任何組件

[英]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.Componentscomponents包含相同的元素,則Intersect將返回非空序列。 如果序列為非空,則不帶參數的Any將返回true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM