在 linq 中使用包含

Using contains in linq

我有一个过滤列表,其中 returns MenuTable

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

我想 select 来自 menutable 的所有项目,它位于 _parentList

这是我尝试过的方法,出现错误 _parentList.Contains(x.Id) 显示 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()

任何帮助将不胜感激

比照。此代码:

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

这会生成一个匿名对象列表,其中一个 属性 称为 MenuParentID,而不是整数列表。编译器为你创建了一个类型,它在结构上看起来像这样(注意编译器在幕后生成了一个不可用的 class 名称而不是 AnonymousType1,但你明白了):

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

_parentList 将是 List<AnonymousType1> 类型。

按如下方式调整您的代码:

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

现在 _parentList 的类型是 List<int>

你可以在msdn上阅读更多关于匿名类型的概念:https://msdn.microsoft.com/en-us/library/bb397696.aspx