2017-06-02 130 views
0

我有以下類。選擇包含特定子元素的對象

public class Bin 
{ 
    public int BinId { get; set; } 
    public IEnumerable<Component> Components { get; set; } 
} 

public class Component 
{ 
    public int ComponentId { get; set; } 
    public string ComponentName { get; set; } 
} 

使用LINQ如何找到包含組特定組件的所有Bin對象,說有ID爲1,2,3組件?

編輯

只是爲了澄清所有的ID必須是存在於Bin。此外我有一個包含ID匹配的集合。

回答

1
var bins = new List<Bin>(); 
var ids = new List<int> { 1, 2, 3 }; 

// go through each bin and make sure it has all the items in ids 
bins.Where(x => ids.All(id => x.Components.Select(c => 
    c.ComponentId).Contains(id))); 
1

像這樣:

bins.Where(b => b.Components.Any(c => new[]{1,2,3}.Contains(c.ComponentId)) 

如果你需要的所有:

bins.Where(b => b.Components.All(c => new[]{1,2,3}.Any(i => i == c.ComponentId))) 

或者,如果您需要在列表中的一些項目有這樣的項目:

bins.Where(b => new[]{1,2,3}.All(i => b.Components.Any(c => i == c.ComponentId))) 

您可以結合全部/任何/包含在子查詢中,如你所願

+0

這將匹配所有垃圾箱比包含ID 1,2至少一個組件,或三個 –

+0

謝謝。我將如何查找包含所有組件的容器。 – erdinger

+0

我已經更新了答案 –

0
bins.Where(x => x.Components.Any(y => y.ComponentId ==1 || y.ComponentId == 2 || y.ComponentId == 3)) 

試試這個。

如果你有整數列表,那麼你可以修改最後的條件,如下所示。

y => list.Any(z => y.ComponentId == z) 

或者類似的東西。

y => list.Contains(y.ComponentId) 

這些條件包含至少一個組件id。如果要包含所有組件ID,您可以使用All方法,而不是Any

1
IEnumerable<int> test = ...; 
bins.Where(x => !test.Except(x.Components.Select(c => c.ComponentId)).Any()); 
相關問題