LINQ查询列表包含列表 [英] Linq query list contains a list
问题描述
我有2类的:
public class ObjectA
{
public int Id;
public string Name;
}
public class ObjectB
{
public int Id;
public string Name;
public List<ObjectA> ListOfObjectA;
}
所以,我有两个列表:一个对象B(ListObjectB)和另一包含对象A的ID的列表(称为ListOfIdsA)。
如果我想要得到的对象B名单,其中ObjectB.ListOfObjectA在ListOfIdsA。
So I have two lists: One of ObjectB (ListObjectB) and Another contains a list of id's of ObjectA (called ListOfIdsA). If this i want to get a list of ObjectB where ObjectB.ListOfObjectA is in the ListOfIdsA.
我的第一个(错误的)方法是
My first (and wrong) approach was
ListObjectB.Where(p=> ListOfIdsA.Contains(p.ListOfObjectA.Select(b=>b.Id)))
不过,这显然会抛出异常。我谷歌,stackoverflowed,但我想,我的搜索技能不是在这个这么好,有谁能够给这个忍者awser?
(prefereably的Lambda前pression)
But this obviously throws an exception. I google it, stackoverflowed, but I'm thinking that my search skills aren't going so well in this, can anybody give a ninja awser of this? (Prefereably in lambda expression)
推荐答案
您试图让ObjectBs的一个列表,其中的所有的的ObjectAs都在ListOfIdsA,或任何他们?
Are you trying to get a list of ObjectBs where all of the ObjectAs are in ListOfIdsA, or any of them?
我想你想要么:
ListObjectB.Where(p => p.ListOfObjectA.Any(x => ListOfIdsA.Contains(x.Id)))
或
ListObjectB.Where(p => p.ListOfObjectA.All(x => ListOfIdsA.Contains(x.Id)))
(您可能想使 ListOfIdsA
A 的HashSet&LT;串&GT;
如果它是显著的大小,顺便说一句。 )
(You may well want to make ListOfIdsA
a HashSet<string>
if it's of significant size, btw.)
这篇关于LINQ查询列表包含列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!