0

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


}
ksg
  • 3,927
  • 7
  • 51
  • 97
  • 1
    Take a look at this: http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property . At the moment `Distinct` will be comparing the anonymous objects it is given by reference, not by the `id` property. – Joel Gregory Nov 05 '15 at 06:03
  • Thanks mate `MoreLINQ` helped me acheive this.. – ksg Nov 05 '15 at 07:14

1 Answers1

0

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();
rorfun
  • 96
  • 6
  • Thanks for the response mate.But above code returns all list instead of filtered one..How can we acheive the above without using `lamba` expression.. – ksg Nov 05 '15 at 06:20