简体   繁体   中英

Get Distinct List using LINQ

I want to translate this query in LINQ format:

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)

This is what I have tried

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()
            };

I am getting all list instead of distinct List

Dashboard VM

 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; }


}

The Distinct() method checks reference equality for reference types. This means it is looking for literally the same object duplicated, not different objects which contain the same values.

Can you try the following? You may need to tweek as I have no testing environment:

        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM