问题描述
在这里,我的LINQ查询要在Table Menu中获取记录,条件是parentID == 0(获取根菜单)和ID!=(parentID列表)(这是父ID列表是具有子菜单菜单的ID) ,我只想加载所有记录,包括没有子记录和子记录的根菜单:
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();
并且我运行此代码,我显示没有子项的记录,不显示儿童记录.有人帮我修复它.我的LINQ新手,非常感谢.
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.
我在这里期望的结果是:没有任何子项的记录列表,我的菜单表架构是:ID,名称,顺序,ParentID.
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-您无需在第一个选择中选择匿名对象,可以写为
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();
始终将集合命名为复数(parentIDs
)
always a good practice to name collections as plural (parentIDs
)
2-无需重复创建new List<>
,因此您可以将所有内容写在一个查询中
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();
答案:首先选择所有叶级子代ID.获取除ParentID列中的值以外的所有ID.然后通过加入leafID从菜单中进行选择
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 };
这篇关于我如何在表中写查询记录具有条件为parentID == 0和ID!=(parentID)的parentID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!