繁体   English   中英

Linq Join选择以返回拼合列表

[英]Linq Join Select to return a flatten List

我有以下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(); 

我的结果是List<ICollection<Permission>> 如何正确执行所有角色的统一列表? 我不知道该怎么做。

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

使用查询语法中的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();

请注意,您需要在Permission实现EqualsGetHashCode才能有意义地使用Distinct

您可以使用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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM