C# 在 LINQ 中查询子集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/521557/
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
Querying Child Collections in LINQ
提问by iasksillyquestions
I have a collection of objects called Gigs
.
我有一组名为Gigs
.
Each Gig
has an Acts
collection.
每个Gig
都有一个Acts
集合。
Using Linq I want to query my collection of gigs to get all gigs where with an act that has an id of 7 for example.
使用 Linq,我想查询我的演出集合以获取所有演出,例如,id 为 7 的行为。
act.id = 7;
So I started writting...
于是我开始写...
return from gig in qry
where gig.Acts //not sure how to do this bit
select gig;
But I'm not sure how you set conditions on the child collection called acts.
但是我不确定您如何在名为acts 的子集合上设置条件。
Any ideas?
有任何想法吗?
回答by Mike_G
var x = gigs.Where(g=>g.Acts.Select(a=>a.ID).Contains(7));
these two queries also return the same:
这两个查询也返回相同的:
var x = gigs.Where(g=>g.Acts.Count(a=>a.ID == 7) > 0);
var x = gigs.Where(g=>g.Acts.FirstOrDefault(a=>a.ID == 7) != null);
回答by Quintin Robinson
Essentially the same as Mike_G, only more verbose syntax and using equality.
本质上与 Mike_G 相同,只是语法更冗长并使用相等性。
var myCollection = from gig in qry
where gig.Acts.Any(act => act.ID == 7)
select gig;
Just an edit to bring comments to the answer:
只需进行编辑即可为答案带来评论:
Actually query is for an ID on a member (Artist) on the Act object that can be null.
实际上,查询是针对可以为空的 Act 对象上的成员(艺术家)的 ID。
new Query:
新查询:
var myCollection = from gig in qry
where gig.Acts.Any(act => (null != act.Artist) && (act.Artist.ID == 7))
select gig;