从主列表中删除子列表
Delete sub list from main list
我在 MVC Identity 工作,想要获得用户没有的角色,所以我创建了 usersWithRoles
LINQ,包含添加到用户的角色,以及 Roles
列表包含所有角色,因此我需要从 Roles
中删除 usersWithRoles
以获取包含用户没有的角色的新列表,
这是我的代码:
public JsonResult GetUserRolesToAdd(string Username)
{
var usersWithRoles = (from user in context.Users.Where(u => u.UserName == Username)
select new
{
UserRoles = (from userRole in user.Roles
join role in context.Roles on userRole.RoleId equals role.Id
select new { RoleName = role.Name, RoleId = role.Id }).ToList()
}).ToList();
var RolesToAdd = (from roles in context.Roles
select new
{
RoleId = roles.Name
}).ToList();
foreach (var item in usersWithRoles)
RolesToAdd.Remove(
//what to write inside removeAll function!
);
var jsonResult = Json(usersWithRoles, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
任何人都可以帮助我!
那.Except()
呢?
var userRoles = new List<string>();
var allRoles = new List<string>();
var missingRoles = allRoles.Except(userRoles);
它将通过删除 userRoles
中包含的所有角色来过滤 allRoles
。
请参阅MS doc。
我在 MVC Identity 工作,想要获得用户没有的角色,所以我创建了 usersWithRoles
LINQ,包含添加到用户的角色,以及 Roles
列表包含所有角色,因此我需要从 Roles
中删除 usersWithRoles
以获取包含用户没有的角色的新列表,
这是我的代码:
public JsonResult GetUserRolesToAdd(string Username)
{
var usersWithRoles = (from user in context.Users.Where(u => u.UserName == Username)
select new
{
UserRoles = (from userRole in user.Roles
join role in context.Roles on userRole.RoleId equals role.Id
select new { RoleName = role.Name, RoleId = role.Id }).ToList()
}).ToList();
var RolesToAdd = (from roles in context.Roles
select new
{
RoleId = roles.Name
}).ToList();
foreach (var item in usersWithRoles)
RolesToAdd.Remove(
//what to write inside removeAll function!
);
var jsonResult = Json(usersWithRoles, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
任何人都可以帮助我!
那.Except()
呢?
var userRoles = new List<string>();
var allRoles = new List<string>();
var missingRoles = allRoles.Except(userRoles);
它将通过删除 userRoles
中包含的所有角色来过滤 allRoles
。
请参阅MS doc。