Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using contains in linq

Tags:

c#

contains

linq

I have a filtered list which returns all the distinctIds from MenuTable

  var _parentList = _employee.Designation.Role.MenuRoles
                                                .Select(x => new
                                                {
                                                    MenuParentID = x.Menu.ParentID
                                                })
                                                .DistinctBy(x => x.MenuParentID)
                                                .OrderBy(x => x.MenuParentID)
                                                .ToList();

I want to select all the items from menutable which is in _parentList

This is what i have tried and an error is coming on _parentList.Contains(x.Id) which says Best overloaded match for System.Generic.contains has some invalid arguments.

 MenuParentList = _db.Menus.Where(x => _parentList.Contains(x.Id))
                           .Select(x => new SMS.Models.ViewModel.DashboardVM.MenuParent
                           {
                               MenuParentID = x.Id,
                               MenuParentName = x.MenuName
                           })
                           .ToList()

Any help will be appreciated

like image 251
ksg Avatar asked Jan 07 '23 05:01

ksg


1 Answers

Cf. this code:

.Select(x => new
{
    MenuParentID = x.Menu.ParentID
})

This results in a list of anonymous objects with one property called MenuParentID, instead of a list of integers. The compiler creates a type for you that structurally looks like this (note that the compiler generates a non-usable class name behind the scenes instead of AnonymousType1, but you get the idea):

class AnonymousType1
{
    public int MenuParentID {get;set;}
}

And _parentList would be of type List<AnonymousType1>.

Adjust your code as follows:

var _parentList = _employee.Designation.Role.MenuRoles
                       .Select(x => x.Menu.ParentID)
                       .Distinct()
                       .OrderBy(id => id)
                       .ToList();

Now _parentList is of type List<int>.

You can read more about the concept of anonymous types on msdn: https://msdn.microsoft.com/en-us/library/bb397696.aspx

like image 194
jeroenh Avatar answered Jan 14 '23 22:01

jeroenh