【问题标题】:How to filter elements by a List item in linq?如何通过 linq 中的列表项过滤元素?
【发布时间】:2014-10-29 14:36:39
【问题描述】:

我有一个用户属于具有特定角色的社区,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; }
}

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

【问题讨论】:

  • 到目前为止,您为实现这一目标做了哪些尝试,您尝试的解决方案遇到了哪些具体问题?
  • 我们可以看看你的UserCommunityRole 课程吗?
  • "假设有一个类 Community"...你为什么不把代码也放到 Community 类中呢?
  • @BenRobinson 我认为 UserCommunityRole 和 CommunityRole 是一样的,他只是有一个错字
  • 这是一个错字。我会改正的,

标签: c# linq entity-framework-6


【解决方案1】:

编辑:

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

【讨论】:

  • CommunityRolesList&lt;UserCommunityRole&gt; 而不是 List&lt;CommunityRole&gt;
  • 在没有建设性意见的情况下投反对票真的很有成效:)
  • 是的,我做到了。这将很好地获得特定的 CommunityRoleType 但不适用于特定的社区。​​span>
  • 你能不能对你的问题既结构又大胆?
  • 我重写了关于清晰度的问题。希望现在已经足够清楚了。
【解决方案2】:

社区中具有 CommunityRoleType Type1 的所有用户

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

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

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2022-01-16
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多