0

I have 2 collections. 1 is an array of groupIds, and the other is an IEnumerable.

My user class contains another list of type IList, which denotes the groups the user belongs to:

 public class User
    {

        public  IList<Group> Groups { get; protected set; }
    }

And the Group class looks something like this:

public class Group{
      public long Group_Id { get; protected set; }
}

What I need to do is return a collection of all users who are in the groupIds array. I.e., I would want something like:

usersRepository.Where(user => user.Groups.Where(group => groupIds.Contains(group.id))

Such that if my groupIds array has group id of 5 and 6, all users in the useresRepository which belong to group 5 and 6 are returned.

So far, the best I've been able to come up with is the following:

UserRepo.Users.AsEnumerable().Where(user =>
            user.GroupUsers.Where(wg => GroupIds.Contains(wg.Group_Id)));

But this is complaining since .Contains returns a boolean instead of my list, but I'm not sure how to fix that.

My code doesn't work due to .Contains() causing the expression to return a boolean rather than a collection. However, I'm not sure how else to check of the list of GroupIds nested within my User object contains the specified group ids.

0

2 Answers 2

2

Try Any .This will give you all the users that have any of the group mentioned in the groupIds array

UserRepo.Users.AsEnumerable().Where(user =>
            user.Groups.Any(wg => GroupIds.Contains(wg.Group_Id)));
Sign up to request clarification or add additional context in comments.

Comments

0

So you have a sequence of Users, where every User has a sequence of Groups, where every Group has a GroupId.

You also have a sequence of GroupIds.

IEnumerable <int> groupIds = 
IQueryable<User> users = ...

You want all Users, that have at least one Group with a GroupId that is in you sequence of GroupIds.

Whenever you see "I want all items that have at least one ...", consider using Any:

var result = users
    .Where(user => user.groups
                       .Select(group => group.groupId)
                       .Any(groupId => groupIds.Contains(groupId));

In words: from every user, take its collection of Groups. From every Group take the groupIds, and check if any of these groupIds is in collection groupIds. If so, keep this user in your result.

This can be a little bit shorter:

var result = users.Where(user => user.groups.Any(group => groupIds.Contains(group.groupId));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.