我有一个分层结果集,如下所示:
然后我有一个这样的自定义对象:
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 = 权限,方法 = 编辑权限和设置权限,操作 = StockEvaluation,方法 = 更新测量。
我正在寻找最有效的解决方案。
我已经尝试过,但它没有让我达到预期的结果:
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()
}
}
});
});
谢谢
最佳答案
您错过了第二次分组 - 当您从 Controller 组中选择操作时:
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();
关于c# - 使用 LINQ 将分层结果集转换为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197457/