0

我得到以下结构:

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

现在我想让所有在同一组中的用户都像要过滤的用户一样。

例如,用户“Theo”属于第一组和第二组。我想要第一组或第二组中的所有用户。

我如何使用 LINQ 或通常的 c# 来实现这一点?

此代码不起作用:

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

Users是我从另一种方法获得的列表,user是 type 的参数User

4

2 回答 2

2

我假设:

  • 该类User具有Groups类型的属性List<Group>
  • 该类Group具有Users类型的属性List<User>

使用 LINQSelectMany方法:

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

或者在查询语法中:

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

更新

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();
于 2013-02-03T13:41:33.173 回答
0

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?

于 2013-02-03T13:56:24.053 回答