LINQ从查询中的对象中选择属性

时间:2013-11-27 18:03:50

标签: c# linq asp.net-mvc-4

我有一个发送邮件的收件人列表,但我想从某个角色中排除那些,问题是我有这个:

var recipients = (from up in _db.UserProfiles
                  join ms in _db.MembershipEntities
                      on up.UserId equals ms.UserId
                  join st in _db.Studios
                      on up.StudioId equals st.StudioId
                  select new
                  {
                      up.UserId,
                      up.UserName,
                      up.StudioId,
                      st.Name,
                      ms.Roles
                  }).ToList();

结果就是我想要的,只是查询返回一个具有RoleID和RoleName的对象Role,所以我不知道如何选择RoleName以便我可以指定要排除的角色。

1 个答案:

答案 0 :(得分:1)

您可以在查询中添加where子句,以过滤特定角色中的用户:

where ms.Roles.All(role => role.RoleName != "<insert role name>")

您的完整查询将如下所示:

(from up in _db.UserProfiles
    join ms in _db.MembershipEntities on up.UserId equals ms.UserId
    where ms.Roles.All(role => role.RoleName != "<insert role name>")
    join st in _db.Studios on up.StudioId equals st.StudioId
    select new { up.UserId, up.UserName, up.StudioId, st.Name, ms.Roles})
    .ToList();