我有以下课程。
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的集合。
发布于 2017-06-02 01:09:46
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)));发布于 2017-06-02 00:26:33
如下所示:
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) ))可以根据需要将子查询中的所有/任意/包含组合在一起
发布于 2017-06-02 00:50:57
IEnumerable<int> test = ...;
bins.Where(x => !test.Except(x.Components.Select(c => c.ComponentId)).Any());https://stackoverflow.com/questions/44318998
复制相似问题