如何将Linq查询的结果分配给字典...
public Dictionary<string, Privilege> GetAllPermissionsByGroupId(string groupid)
{
string[] Roles = new string[] { "e8b08a45-9cb5-4ac9-8c6c-9dfe4ac23966$Moderator" };
List<RolePrivilege> RoleList = new List<RolePrivilege>();
List<Privilege> PrivilegeList = new List<Privilege>();
Dictionary<string, RolePrivilege> Role = PrivilegeProxy.GetPrivilegesForRoles("744A2BE3-846E-4E4A-9796-DAF9C743E8FF", Roles);
RoleList = Role.Values.ToList();
Dictionary<string, Privilege> Privilege = PrivilegeProxy.GetPrivilegesbyModuleIds(new string[] { "Groups" });
PrivilegeList = Privilege.Values.ToList();
var identicalQuery = from roles in RoleList
join privileges in PrivilegeList on roles.PrivilegeName equals privileges.Name
select new { Roles = roles, Privileges = privileges };
Dictionary<string, Privilege> Result=new Dictionary<string,Privilege>();
Result=?
return Result;
}
答案 0 :(得分:1)
实际上,您的代码并未说明您希望将其放入字典中。什么应该是关键?与RolePrivilege关联的字符串?
没关系,我建议你在词典中使用对而不是值:
var Roles = new string[] { "e8b08a45-9cb5-4ac9-8c6c-9dfe4ac23966$Moderator" };
Dictionary<string, RolePrivilege> Role = PrivilegeProxy.GetPrivilegesForRoles("744A2BE3-846E-4E4A-9796-DAF9C743E8FF", Roles);
Dictionary<string, Privilege> Privilege = PrivilegeProxy.GetPrivilegesbyModuleIds(new string[] { "Groups" });
var identicalQuery = from roles in Role
join privileges in Privilege on roles.Value.PrivilegeName equals privileges.Value.Name
select new { Roles = roles, Privileges = privileges };
Dictionary<string, Privilege> Result = identicalQuery.ToDictionary(_ => _.Roles.Key, _.Privileges.Value);
<强> EDITED 强>
好的,让我们想象两个词典的内容:
您对输出的期望是什么? 我想你想要下一个顺序:
正确?如果是,此请求将有所帮助:
var Result = Role
.Join(Privilege,
outer => outer.Key,
inner => inner.Key,
(outer, inner) => new { Str = outer.Key, Privilege = inner.Value })
.ToDictionary(_ => _.Str, _ => _.Privilege);
答案 1 :(得分:0)
您可能正在寻找Enumerable.ToDictionary()
,但我只能猜测您正在尝试做什么......
var query = from employee in employees
join privilege in privileges
on employee.PrivilegeName equals privilege.Name
select new
{
Employee = employee,
Privilege = privilege
};
var dictionary = query.ToDictionary(o => o.Employee);
您的变量令人困惑,因为employeeA
的类型为RolePrivilege
而employeeB
的类型为Privilege
。此外,最好是在ID而不是名称上进行连接(如果可能的话)。
也许这个问题会有所帮助:
Linq-to-SQL ToDictionary()