h.salman h.salman -4 years ago 339
C# Question

Querying C# Dictionary using Lambda expressions

Let' say I have this Declared Dictionary:

private static Dictionary<int, List<Models.APIAccessControl>> _APIRights = GetAPIRights();

Where the key represents the roleId, the value represent the class:

public class APIAccessControl
public APIControllerRoute ControllerRoute { get; set; }
public APIActionRoute ActionRoute { get; set; }
public bool IsAuthorized { get; set; }


I am trying to check if the user is authorized to access this api.
My idea is to query the dictionary and get all list of APIAccessControl for the roles, then query those APIAccessControl lists for the APIActionRoute he is trying to navigate:

I got the Dictionary Values that contain those list for the roles i want, but how to cast a List of Values to List and make this query:

public static bool CanAccess(int[] roleIDs, APIActionRoute apiActionRoute)
bool canAccess = false;

var apiAccessList = _APIRights.Where(x => roleIDs.Contains(x.Key)).Select(x => new { x.Value}).ToList();

//Querying to get all List<Models.APIAccessControl> that has any matchig APIActionRoute

Answer Source

You can modify the Select clause to give you the list you want:

var apiAccessList = _APIRights.Where(x => roleIDs.Contains(x.Key))
    .SelectMany(x => x.Value).ToList();

By not selecting to an anonymous class and by using the SelectMany, the list will be of type Models.APIAccessControl

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download