从主列表中删除子列表

时间:2018-09-18 09:08:23

标签: c# list model-view-controller identity

我正在使用MVC Identity,并且想获得用户没有的角色,因此我创建了usersWithRoles LINQ,包含添加到用户的角色,并且Roles列表包含所有角色,因此我需要从usersWithRoles中删除Roles,以获取一个新列表,其中包含用户没有的角色, 这是我的代码:

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;
}

任何人都可以帮助我!

1 个答案:

答案 0 :(得分:0)

.Except()呢?

var userRoles = new List<string>();
var allRoles = new List<string>();

var missingRoles = allRoles.Except(userRoles);

它将通过删除allRoles中包含的所有角色来过滤userRoles

请参阅MS doc

相关问题