使用LINQ获取Distinct List

时间:2015-11-05 05:52:50

标签: c# linq asp.net-mvc-4

我想以LINQ格式翻译此查询:

select m.MenuName,m.ParentID from Menu m where Id in(
select distinct m.ParentID from Menu m inner join MenuRole  mr on mr.MenuID=m.Id)

这就是我试过的

var _employee = _db.Employees.AsEnumerable().Where(e => e.Id == Int32.Parse(Session["LoggedUserId"].ToString()))
                                           .FirstOrDefault();
var _dashboardVM = new DashboardVM
            {                    
                MenuParentList = _employee.Designation.Role.MenuRoles                                            
                                                .Select(x => new SMS.Models.ViewModel.DashboardVM.MenuParent
                                                { 
                                                    MenuParentID=x.Menu.ParentID ,
                                                    MenuParentName=x.Menu.MenuName

                                                })
                                                .Distinct().ToList()
            };

我得到所有列表而不是不同的列表

仪表板虚拟机

 public class DashboardVM
{
    public class MenuParent
    {
        public int? MenuParentID { get; set; }
        public string MenuParentName { get; set; }
    }
    public List<MenuParent> MenuParentList { get; set; }
    public List<Menu> MenuList { get; set; }
    public User User { get; set; }


}

1 个答案:

答案 0 :(得分:0)

Distinct()方法检查引用类型的引用相等性。这意味着它在字面上寻找相同的对象,而不是包含相同值的不同对象。

您可以尝试以下方法吗?你可能需要调整,因为我没有测试环境:

        MenuParentList = _employee.Designation.Role.MenuRoles.GroupBy ( r => r.Menu.ParentID + r.Menu.MenuName ).
                                        .Select (y => y.First ())
                                        .Select(x => new SMS.Models.ViewModel.DashboardVM.MenuParent
                                        { 
                                            MenuParentID=x.Menu.ParentID ,
                                            MenuParentName=x.Menu.MenuName

                                        }).ToList();
相关问题