如何通过linq中的List项过滤元素?

时间:2014-10-29 14:36:39

标签: c# linq entity-framework-6

我有一个属于具有特定角色的社区的用户,User,Community,CommunityRole和CommunityRoleType的类别如下所示:

public class User{
    public int UserId { get; set;}  
    public List<CommunityRole> CommunityRoles { get; set; }
}

public class Community{
    public int CommunityId { get; set;}
    public string Name { get; set; }
}
public enum CommunityRoleType{
    Type1,
    Type2
}
public class CommunityRole { 
    public Community Community { get; set; }
    public CommunityRoleType RoleType {get; set; }
}

如何从用户列表中获取属于特定社区并被分配特定角色的用户子集?

2 个答案:

答案 0 :(得分:1)

编辑:

var usersType1 = users.Where(usr => usr.CommunityRoles.Any(role => 
                              role.RoleType == CommunityRoleType.Type1
                                   && role.Community.CommunityId == communityID)).ToList();

答案 1 :(得分:0)

  

社区中拥有CommunityRoleType Type1

的所有用户

如果只有您说过“社区中的所有用户”(即您之前提及的社区):

var users = _context.Users
            .Where(u => u.CommunityRoles
                         .Any(cr => cr.RoleType == CommunityRoleType.Type1
                                 && cr.Community.CommunityId == someCommunityId ));