使用 LINQ 将分层结果集转换为自定义对象

Translate hierarchical result set to custom object using LINQ

我有一个像这样的分层结果集:

然后我有一个这样的自定义对象:

public class AuthorizedEntity
{
    public Departments Department { get; set; }

    public string Username { get; set; }

    public List<AuthController> Controllers = new List<AuthController>();        
}

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

    public List<AuthAction> Actions = new List<AuthAction>();
}

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

    public List<string> Methods = new List<string>();
}

是否可以将以下数据转换为相应的对象?在这种特殊情况下,用户名是 justinfarrugia,Controller = StocktakeController,Actions = Permissions with Methods = Edit Permissions and Set Permissions and Action = StockEvaluation with Method = Update Measurements.

我正在寻找最有效的解决方案。

我试过了,但没有达到预期的效果:

ObjectResult<SP_GetPrivilegesByUsername_Result> lstAuthorizedUsersRaw = dbsp.SP_GetPrivilegesByUsername(inUsername.Trim());
        lstAuthorizedUsersRaw.GroupBy(p => p.Cntrollers_Name).ToList().ForEach(r =>
        {
            authEntity.Controllers.Add(new AuthController()
            {
                Name = r.Key,
                Actions = new List<AuthAction>() {
                                                    new AuthAction() {
                                                                        Name = r.ToList().Select(q => q.HMVAct_Name).FirstOrDefault(),
                                                                        Methods = r.ToList().Select(w => w.HMVMethd_Name).ToList()

                                                                     }
                                                 }
            });
        });

谢谢,

您错过了第二个分组 - 当您 select 来自控制器组的操作时:

var lstAuthorizedUsersRaw = dbsp.SP_GetPrivilegesByUsername(inUsername.Trim());

authEntity.Controllers = lstAuthorizedUsersRaw
      .GroupBy(p => p.Cntrollers_Name)
      .Select(controllerGroup => new AuthController {
         Name = controllerGroup.Key,
         Actions = controllerGroup
                    .GroupBy(p => p.HMVAct_Name) // here
                    .Select(actionGroup => new AuthAction {
                        Name = actionGroup.Key,
                        Methods = actionGroup.Select(pu => p.HMVMethd_Name).ToList()
                    }).ToList()
      }).ToList();