si2030
si2030

Reputation: 4045

asp.net mvc Problems with simple LINQ statement with a list within a list

I have been putting together a dynamic menu in asp.net-core MVC 6 using this Blog.

I have a menuItem object that I wish to select a subset of objects based on two criteria. Here is the Menu Object:

 public class MenuItem
{
    public int Id { get; set; }
    public bool Divider { get; set; }
    public bool Header { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public string MenuItemText { get; set; }
    public IList<string> Roles { get; set; }
    public int ParentId { get; set; }

    public MenuItem()
    {

    }

    public MenuItem(int id, bool divider, bool header, string action, string controller, string menuItemText, IList<string> roles,int parentid)
    {
        Id = id;
        Divider = divider;
        Header = header;
        ActionName = action;
        ControllerName = controller;
        MenuItemText = menuItemText;
        Roles = roles;
        ParentId = parentid;
    }
 }

A list of these items was populated using a line like:

MenuList.MenuItems.Add(new MenuItem(100, false, false, "Index", "Scheduler", "Scheduling", new List<string>() { "Admin", "Technician" }, 0));

I can select those MenuItems based on ParentId using this line and it works:

_menuData.GetUnAuthorizedMenus().Result.MenuItems.Where(s => s.ParentId == parentId).ToList();

and in particular:

MenuItems.Where(s => s.ParentId == parentId).ToList();

How do I select those lines where ParentId == parentId and

Roles == "Admin".

In menuItem there is a list of roles this MenuItem belongs to and I want to select those items based on whether they have a specific role in that list.

How do you select only those menuItems with a specific role in the sublist as well as ParentId as above...

Upvotes: 0

Views: 85

Answers (2)

Alastair Brown
Alastair Brown

Reputation: 1616

This should work

MenuItems.Where(s => s.ParentId == parentId && s.Roles.Contains("Admin")).ToList();

or maybe

MenuItems.Where(s => s.ParentId == parentId && s.Roles.Count() == 1 && s.Roles.Contains("Admin")).ToList();

If you want menu items with only the Admin role

Upvotes: 2

Atul Chaudhary
Atul Chaudhary

Reputation: 3736

Try this it should return record where Id = parent id and sublist where role is admin.

menuItems.Where(x => x.Id == parentId).Where(z => z.Roles.Any(y => y == "Admin"));

And if you want to filter sublist also then use

menuItems.Where(x => x.Id == parentId).select(child => new MenuItems
{
//Populate parent properties
Roles = child.Roles.Where(x=>x=="Admin")
});

Upvotes: 1

Related Questions