简体   繁体   中英

C# Linq query to return Dictionary<int,int[]>

Ok, so I have a need to create/return a Dictionary from the results of a Linq Query. I have tried just about everything I can think of and keep running into issues. Here is what I am currently attempting...

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;
        }
    }

any help at all would be greatly appreciated. what i am looking for to be returned from this is a Dictionary where the Key is the entityId or EntityManager.EntityId and the Value(s) are an array of associated RoleId's.

Currently I am getting the following two errors at compile time, and other attempts have been errors similar but not exact to these.

Error 11 The type arguments for method 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable, System.Func<TSource,TKey>, System.Collections.Generic.IEqualityComparer<TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Error 12 Cannot implicitly convert type 'System.Collections.Generic.Dictionary<TKey,Sqor.Database.DbEntityManagerRoleAssignment>' to 'System.Collections.Generic.Dictionary<int,int[]>'

UPDATE - Working Solution (Thanks to @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;
        }
    }

It sounds like you want to group by the Entity ID and project the associated role IDs to an array:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM