2017-06-02 84 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()); 
相关问题