user2381733
user2381733

Reputation: 27

Collections list and dictionary

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

Answers (4)

Dave Bish
Dave Bish

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

user2385939
user2385939

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

Francesco De Lisi
Francesco De Lisi

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

Alex Filipovici
Alex Filipovici

Reputation: 32581

Try this:

var distinct = Links
    .Where(i => roleids.Contains(i.Key))
    .SelectMany(i => i.Value).Distinct()
    .ToList();

Upvotes: 0

Related Questions