Reputation: 27
I have a list that contains roleids and a dictionary that has database of roleids and menus accessible to that roleid.
Suppose a user has role 1,2,3
then how do I retrieve the distinct menus he can access from a dictionary?
List<int> roleids = new List<int>();
roleids.Add(1);
roleids.Add(2);
roleids.Add(3);
Dictionary<int, List<String>> Links = new Dictionary<int, List<string>>
{
{ 1, new List<String> { "Home", "About Us", "Logout", "Help" } },
{ 2, new List<String> { "Home", "Products", "Logout", "Help" } },
{ 3, new List<String> { "Home", "Customers", "Users", "Help" } }
};
I want to create a new list that contains menus accessible to user based on values in List roleids
Upvotes: 0
Views: 141
Reputation: 19656
If you do your initial select across the roleids
list - you can leverage the fast-lookup nature of the dictionary
var menuItems = roleids
.Select(id => Links[id])
.SelectMany(roles => roles)
.Distinct();
Upvotes: 7
Reputation: 1
use this algorithm
public static List<string> GetMenuItems(List<int> userRoles)
{
var roleids = new List<int>();
roleids.Add(1);
roleids.Add(2);
roleids.Add(3);
var Links = new Dictionary<int, List<string>>()
{
{1,new List<String> {"Home","About Us","Logout","Help"}},
{2,new List<String>{"Home","Products","Logout","Help"}},
{3,new List<String>{"Home","Customers","Users","Help"}}
};
var roleLinks = Links
.Where(item => userRoles.Contains(item.Key))
.SelectMany(item => item.Value)
.ToList()
.Distinct();
}
Upvotes: 0
Reputation: 1523
Retrieve at first Links where role id in user's roleids, then select from this subset the values and avoid duplicates with distinct:
var menus = Links.Where(l => roleids.Contains(l.key))
.SelectMany(k => k.Value)
.Distinct();
Upvotes: 0
Reputation: 32581
Try this:
var distinct = Links
.Where(i => roleids.Contains(i.Key))
.SelectMany(i => i.Value).Distinct()
.ToList();
Upvotes: 0