[c#]Linq 嵌套组以操纵标识数据

标签: Linq C#
发布时间: 2017/2/28 21:18:47
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

嗨我有一直试着改变一个数据结构的形状变成另一种没有运气的几天。

原始的数据结构如下所示。

public class Role : IdentityRole
{
    public string Name { get; set; }
    public virtual List<PermissionInRole> PermissionsInRole { get; set; }
}

public class PermissionInRole
{
    public Guid Id { get; set; }
    public virtual Permission Permission { get; set; }
    public virtual Feature Feature { get; set; }
}

public class Permission
{
    public Guid Id { get; set; }

    public string Description { get; set; }
}

public class Feature
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual Application Application { get; set; }
}

public class Application
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual List<Feature> Features { get; set; }
}

若要使用 Linq 将它更改为此形状 !

public class ApplicationApiModel
{
    public string Name { get; set; }

    public ICollection<FeaturesApiModel> Features { get; set; }
}

public class FeaturesApiModel
{
    public string Name { get; set; }

    public IEnumerable<PermissionsApiModel> Permissions { get; set; } 
}

public class PermissionsApiModel
{
    public string PermissionName { get; set; }

    public IEnumerable<Role> Role { get; set; }
}

public class Role
{
    public string Name { get; set; }
}

我想要应用程序集合,包含一个功能集合,包含的权限,一个包含有父权限的角色的集合的集合。

我敢肯定,这可以用 linq 然而我却引不起任何的帮助会很大。

解决方法 1:

经过多次尝试我结束了下面的工作代码

            var query = from role in roles
                    group role by role.PermissionsInRole
                        into g
                        select new
                        {
                            PinR = g.Key,
                            role = g.ToList()
                        };

        var transferList = (from w in query
            from pr in w.PinR
            select new
            {
                Feature = pr.Feature, Permission = pr.Permission, TransferRole = w.role.Single()
            })
            .ToList()
            .GroupBy(o => o.Feature, (key, o) =>
            new FeaturesApiModel
            {
                Name = key.Name,
                Permissions = o.GroupBy(transferObject => transferObject.Permission, (subKey,transferObject) =>
                    new PermissionsApiModel
                    {
                        PermissionName = subKey.Description,
                        Role = transferObject.Select(flatTransferObject => new RoleAPIModel {Name = flatTransferObject.TransferRole.Name})
                    }
                )
            });
官方微信
官方QQ群
31647020