我有一个情况;用户附加了多个角色,如下面的json中所示
[
{
"userid" : 1,
"roleid" : 1
},
{
"userid" : 1,
"roleid" : 2
}
]
并且每个角色都包含许多功能权限(下面的json)
[
{
"roleid" : 1,
"FeatureName": "AddUser",
"Accessible": true,
},
{
"roleid" : 1,
"FeatureName": "AddEmp",
"Accessible": true,
},
{
"roleid" : 2,
"FeatureName": "AddUser",
"Accessible": false,
},
{
"roleid" : 2,
"FeatureName": "AddEmp",
"Accessible": false,
}
]
我需要一个linq查询,选择为该用户选择最佳权限列表。 我目前在列表下方(在Json中)
[
{
"accessid": 1,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddUser",
"Accessible": true,
},
{
"accessid": 2,
"roleid" : 2,
"userid" :1,
"FeatureName": "AddUser",
"Accessible": false,
},
{
"accessid": 3,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddEmp",
"Accessible": true,
},
{
"accessid": 4,
"roleid" : 2,
"userid" :1,
"FeatureName": "AddEmp",
"Accessible": false,
},
{
"accessid": 5,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddRoles",
"Accessible": false,
}
]
我现在想要的只是为用户设置了一组乐观权限,如下所示
[
{
"accessid": 1,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddUser",
"Accessible": true,
},
{
"accessid": 3,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddEmp",
"Accessible": true,
},
{
"accessid": 5,
"roleid" : 1,
"userid" :1,
"FeatureName": "AddRoles",
"Accessible": false,
}
]
PS:我不会为json中的角色错过而烦恼。
我尝试了许多linqs但无法到达所需的json。任何帮助表示赞赏。
答案 0 :(得分:0)
假设您有一个类名Access
作为结果模型
public class Access
{
public int accessid { get; set; }
public int roleid { get; set; }
public int userid { get; set; }
public string FeatureName { get; set; }
public bool Accessible { get; set; }
}
而且你找到了一种方法来查询用户的Access
,然后你可以使用LINQ以下来优化结果
编辑已更新,因此结果包含拒绝(Accessible=false
)结果
var optimised = from o in accesses
group o by new { o.userid, o.FeatureName } into g
select new Access()
{
userid = g.Key.userid,
FeatureName = g.Key.FeatureName,
//OrderByDescending put the true before the false
Accessible = g.OrderByDescending(t => t.Accessible).First().Accessible,
//you might want to comment the accessid and roleid
accessid = g.First().accessid,
roleid = g.First().roleid,
};