【问题标题】:C# Linq query to return Dictionary<int,int[]>C# Linq 查询返回 Dictionary<int,int[]>
【发布时间】: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 =&gt; x.EntityManager.EntityId, x =&gt; x.RoleId) 行中的内容。但是这里RoleId 不是数组。

标签: c# arrays linq dictionary int


【解决方案1】:

听起来您想按实体 ID 分组并将关联的角色 ID 投影到数组:

using (MyDb db = new MyDb())
{
    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;
}

【讨论】:

  • 试试这个。谢谢 D 斯坦利。
  • 我认为这很完美 D Stanley,在第一次运行时,它似乎有 3 个条目,第一个是正确的,第二个是 0,0。但是,在代码块完成后,GetEntityAuthorizations 只有一组,这将是正确的。
  • 很高兴它成功了。通过检查它们来调试 Linq 查询可能很棘手。通常您需要查看最终结果,而不是尝试检查中间结果。
  • 是的,完全正确,而且我很难得到任何半正确的东西来看到最终结果。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多