0

I have the following Linq statement:

var permissions = (from ru in RoleUserStore
                  join role in RoleStore on ru.RoleId equals role.Id
                  where ru.UserId == user.Id
                  select role.Permissions).ToList(); 

My result is a List<ICollection<Permission>>. How do I do this correctly to have a flat List across all the Roles? I could not figure out how to do this.

4

3 回答 3

4

替换ToList()SelectMany(x => x).ToList()

于 2013-10-16T10:55:05.867 回答
3

SelectMany在查询语法中使用which is:

var permissions = from ru in RoleUserStore
                  join role in RoleStore on ru.RoleId equals role.Id
                  where ru.UserId == user.Id
                  from permission in role.Permissions
                  select permission;

 // if you don't want repeating permissions use Distinct:
List<Permission> permissionList = permissions.Distinct().ToList();

请注意,您需要实现Equals并有意义GetHashCodePermission使用。Distinct

于 2013-10-16T10:58:58.857 回答
0

您可以使用SelectMany

var result = (from ru in RoleUserStore
              join role in RoleStore on ru.RoleId equals role.Id
              where ru.UserId == user.Id
              select role.Permissions)
              .SelectMany(user => user).ToList();

这就是 SelectMany 所做的,我引用了 MSDN。

Projects each element of a sequence to an IEnumerable(Of T) and flattens the resulting sequences into one sequence.

于 2013-10-16T10:56:29.877 回答