How can i write query record in table have parentI

2019-08-26 20:45发布

Here i my LINQ query to get record in Table Menu with condition are parentID == 0(get root menu) and ID != (parentID list) (which is parent ID list is are id of menu record that have child), i just want to load all record includes root menu that have no children record and children record :

List<Menu> menus = MenuDAO.Instance.GetAll(); // Get All Record in Menu Table
var parentID = (from p in menus where p.ParentID != 0 select new {p.ParentID}).Distinct(); // Get unique ParentID in Menu Table
        List<int> numParentID = new List<int>();
        foreach (var a in parentID)
        {
            numParentID.Add(a.ParentID);
        } // assign to a list <int>
        this.ddlMenu.DataSource = from m1 in menus
                                  where !(numParentID).Contains((int)m1.ID) && m1.ParentID == 0
                                  select new { m1.ID, m1.Name };
        this.ddlMenu.Databind();

And i run this code , i display record that have no children, do not display chilren record. Somebody help me fix it. My new in LINQ , thanks a lot.

The Result as i expect here is : list of record that do not have any children, my Menu table schema is : ID, Name, Order, ParentID.

1条回答
We Are One
2楼-- · 2019-08-26 21:26

Suggestions

1-You don't need to select an anonymous object in the first select, you could write as

var parentIDs = (from p in menus 
                 where p.ParentID != 0 
                 select p.ParentID).Distinct();

always a good practice to name collections as plural (parentIDs)

2-No need to iterate to create a new List<>, so you can write all of them in one query

  List<int> numParentIDs = (from p in menus 
                            where p.ParentID != 0 
                            select p.ParentID).Distinct().ToList();

Answer : first select all the leaf level children IDs. Get all ID except the values in the ParentID column. And then do a select from menu by joining the leafIDs

var leafMenuIDs = menus
                    .Select(m => m.ID)
                    .Except(menus.Select(m => m.ParentID).Distinct())                                         
                    .Distinct();


 this.ddlMenu.DataSource = from m in menus
                           join id in leafMenuIDs on m.ID equals id
                           select new { m.ID, m.Name };
查看更多
登录 后发表回答