简体   繁体   English

使用LINQ获取不同的列表

[英]Get Distinct List using LINQ

I want to translate this query in LINQ format: 我想将此查询转换为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)

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 仪表板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. Distinct()方法检查引用类型的引用相等性。 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: 您可能需要tweek,因为我没有测试环境:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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