views:

154

answers:

2

Hello, 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 possible to make a query that retreives all the sections where there is at least one group within the groups user class?

Any help?

+1  A: 
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

Andreas Niedermair
I thank you... it seems to be ok..
Stan92
as long as you work on the exact same reference... like marc said ... otherwise you can include a Func<Group, bool> in your .Any()-call to get eg. check for ids. see http://msdn.microsoft.com/en-us/library/system.linq.enumerable.any.aspx
Andreas Niedermair
I'm a bit curious how to use the Func<Group,bool) using the Mark's method.Anyway I thank you all
Stan92
eg. `.Any(userGroup => userGroup.Id == sectionGroup.Id)` - you can also instatiate your `IEqualityComparer<Group>` and do sth like `.Any(userGroup => myInstanceOfMyComparer.Equals(userGroup, sectionGroup))`. another method would be to implement `IEquatable<Group>` on `Group`
Andreas Niedermair
+2  A: 
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)

Marc Gravell
@Marc: I always learn something from you. Like till today I never noticed the 'parameterless' `Any` method :)
leppie