[英]Linq Join Select to return a flatten List
I have the following Linq statement: 我有以下Linq声明:
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>>
. 我的结果是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. 我不知道该怎么做。
用SelectMany(x => x).ToList()
替换ToList()
SelectMany(x => x).ToList()
。
Use SelectMany
which is in query syntax: 使用查询语法中的SelectMany
:
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();
Note that you need to implement Equals
and GetHashCode
in Permission
to use Distinct
meaningfully. 请注意,您需要在Permission
实现Equals
和GetHashCode
才能有意义地使用Distinct
。
You can use SelectMany 您可以使用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();
This is what SelectMany does and I quote MSDN. 这就是SelectMany所做的,我引用了MSDN。
Projects each element of a sequence to an IEnumerable(Of T) and flattens the resulting sequences into one sequence.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.