Knerd
Knerd

Reputation: 2002

LINQ filter with or

I got the following structure:

 One user can have many Groups and a Group can have many users.

Now I want to get all users that are in the same group like the user to filter by.

For example, The user "Theo" is in Group one and two. I want all users that are in Group one OR Group two.

How can I achive this with LINQ or generally c#?

This code doesn't work:

var res = (IEnumerable<User>)Users;
foreach (var item in user.Groups) {
    res = res.Where(usr => usr.Groups.Contains(item));
}
return res.ToList();

Users is a list I got from another method and user is a parameter of type User.

Upvotes: 0

Views: 86

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Perhaps using Intersect.Any on the groups:

var groupsFind = new []{"Group1","Group2"};
var userFound = allUsers
    .Where(u => u.Groups
                 .Select(ug => ug.Name)
                 .Intersect(groupsFind)
                 .Any());

I don't understand the model, a user belongs to n groups and every group can have n users. Isn't the last relation redundant or the same as the first just vice-versa?

Upvotes: 0

C&#233;dric Bignon
C&#233;dric Bignon

Reputation: 13022

I assume:

  • The User class has a property Groups of type List<Group>
  • The Group class has a property Users of type List<User>

Use the LINQ SelectMany method:

var usersInSameGroups = user.Groups.SelectMany(group => group.Users).ToList();

Or in query-syntax:

var usersInSameGroups = (from g in user.Groups
                         from userInGroup in g.Users
                         select userInGroup).ToList();

UPDATE

return (from user2 in Users
        where user2.Groups.Intersect(user.Groups).Any()  // Keeps only user2 if it has a common group with user
        select user2).ToList();

Upvotes: 2

Related Questions