c# Linq Object subQuery / In
I have 2 objects that contains generic list properties. IE :
public class User
{
public string Sid { get; set; }
public List<Group> Groups { get; set; }
}
public class Section
{
public string Sid { get; set; }
public List<Group> Groups { get; set; }
}
From my BLL I get a generic list of sections List mySections=SectionDB.getList();
and my User object contains the user Information User myUser=UserDB.getInfo(sid);
Using linq to objects, is it p开发者_运维问答ossible to make a query that retreives all the sections where there is at least one group within the groups user class?
Any help?
from section in mySections
from sectionGroup in section.Groups
where myUser.Groups.Any(userGroup => userGroup == sectionGroup)
select section
i'd rather go for any, as you use the iterator much more efficiently
var sections = mySections.Where(x => x.Groups.Intersect(myUser.Groups)
.Any()).ToList();
(note that this relies on either referential equality of the Group
instances, or a suitable Equals
/ GetHashCode
implementation on the Group
type)
精彩评论