C# Linq 查询列表包含一个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2364090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq query list contains a list
提问by Berto
I have 2 a class's:
我有两个班级的:
public class ObjectA
{
public int Id;
public string Name;
}
public class ObjectB
{
public int Id;
public string Name;
public List<ObjectA> ListOfObjectA;
}
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.
所以我有两个列表:一个 ObjectB (ListObjectB) 和另一个包含 ObjectA 的 id 列表(称为 ListOfIdsA)。如果这是我想获得 ObjectB 的列表,其中 ObjectB.ListOfObjectA 在 ListOfIdsA 中。
My first (and wrong) approach was
我的第一个(也是错误的)方法是
ListObjectB.Where(p=> ListOfIdsA.Contains(p.ListOfObjectA.Select(b=>b.Id)))
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)
但这显然会引发异常。我谷歌它,stackoverflowed,但我认为我的搜索技巧在这方面不太好,任何人都可以给这个忍者awser吗?(最好在 lambda 表达式中)
采纳答案by Jon Skeet
Are you trying to get a list of ObjectBs where allof the ObjectAs are in ListOfIdsA, or anyof them?
您是否正在尝试获取所有ObjectA 都在 ListOfIdsA 或其中任何一个中的 ObjectB 列表?
I think you want either:
我想你想要:
ListObjectB.Where(p => p.ListOfObjectA.Any(x => ListOfIdsA.Contains(x.Id)))
or
或者
ListObjectB.Where(p => p.ListOfObjectA.All(x => ListOfIdsA.Contains(x.Id)))
(You may well want to make ListOfIdsA
a HashSet<string>
if it's of significant size, btw.)
(顺便说一句,如果它的尺寸很大,您可能想要制作ListOfIdsA
一个HashSet<string>
。)