How can i write query record in table have parentID with condition parentID == 0 and ID != (parentID)
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
开发者_StackOverflow 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.
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 };
精彩评论