【发布时间】:2016-07-12 14:46:35
【问题描述】:
好的,所以我需要从 Linq 查询的结果中创建/返回字典。我已经尝试了几乎所有我能想到的并不断遇到问题。这是我目前正在尝试的...
public static Dictionary<int,int[]> GetEntityAuthorizations(int userId)
{
using (MyDb db = new MyDb())
{
var query = db.EntityManagerRoleAssignments.Where(x => x.EntityManager.ManagerId == userId);
var entityId = query.Select(x => x.EntityManager.EntityId);
var roles = query.Select(x => x.RoleId).ToArray();
var result = query.ToDictionary(entityId, roles);
return result;
}
}
任何帮助都将不胜感激。我希望从中返回的是一个字典,其中键是 entityId 或 EntityManager.EntityId,值是关联 RoleId 的数组。
目前我在编译时遇到以下两个错误,其他尝试也出现了类似但不完全相同的错误。
错误 11 方法 'System.Linq.Enumerable.ToDictionary
(System.Collections.Generic.IEnumerable, System.Func , System.Collections.Generic.IEqualityComparer 的类型参数>)' 不能从用法中推断出来。尝试明确指定类型参数。 错误 12 无法将类型 'System.Collections.Generic.Dictionary
' 隐式转换为 'System.Collections.Generic.Dictionary '
更新 - 工作解决方案(感谢 @D Stanley)
public static Dictionary<int,int[]> GetEntityAuthorizations(int userId)
{
using (SqorDb db = new SqorDb())
{
var query = db.EntityManagerRoleAssignments.Where(x => x.EntityManager.ManagerId == userId);
var entityGroups = query.GroupBy(x => x.EntityManager.EntityId);
var result = entityGroups.ToDictionary(e => e.Key,
g => g.Select(x => x.RoleId).ToArray()
);
return result;
}
}
【问题讨论】:
-
它目前在做什么与您希望它做什么?
-
你为什么想要一本只有一对的字典?该方法采用单个用户 ID,因此该字典不会包含多个键值对。让它返回一个
int[]。 -
你的权利,我已经编辑了我的代码以更好地显示我所追求的......
-
键将是 entityId,对不起。
-
您只是想将两个可枚举对象粉碎在一起。您可能正在寻找
query.ToDictionary(x => x.EntityManager.EntityId, x => x.RoleId)行中的内容。但是这里RoleId不是数组。
标签: c# arrays linq dictionary int