使用联接和分组简化两个LINQ查询

时间:2019-01-31 18:41:36

标签: c# linq

我有两个静态类,其中的字段用DisplayAttribute装饰。其中一个包含描述各个策略的字段,这些策略指示其在属性中的父角色。另一个静态类包含描述角色字段。

如何结合q1q2,目前我不清楚如何执行发生在分组q2,并保留的范围的role

var roles = typeof(AuthRoles).GetFields(BindingFlags.Public | BindingFlags.Static)
    .Select(p => p.GetCustomAttribute<DisplayAttribute>())
    .OrderBy(a => a.Order)
    .Select(a => new { Id = a.ShortName, a.Name, a.Description, a.Order });

var policies = typeof(AuthPolicies).GetFields(BindingFlags.Public | BindingFlags.Static)
    .Select(p => p.GetCustomAttribute<DisplayAttribute>())
    .Select(a => new { Id = a.ShortName, a.Name, RoleId = a.GroupName, a.Description });

var q1 =
    from role in roles
    join policy in policies on role.Id equals policy.RoleId
    select new { role, policy };

var q2 =
    from item in q1
    group item by item.role.Id
    into grp
    select new
    {
        Role = grp.Select(g => new
        {
            Id = g.role.Id,
            Name = g.role.Name,
            Description = g.role.Description,
            Order = g.role.Order
        }).First(),
        Policies = grp.Select(g => new
        {
            Id = g.policy.Id,
            Name = g.policy.Name,
            Description = g.policy.Description
        }).OrderBy(a => a.Name).ToArray()
    };

1 个答案:

答案 0 :(得分:0)

您不需要join中的两个来源,q1中将它们分组,则可以使用LINQ组联接直接收集该组:

q2