我如何在具有parentID的表中写入查询记录,条件为parentID == 0且ID != (parentID)
这里我的 LINQ 查询获取表菜单中的记录,条件是parentID == 0(获取根菜单)和ID!=(parentID列表)(这是父ID列表是有子菜单记录的id),我只是想要加载所有记录,包括没有子记录的根菜单和子记录:
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,非常感谢。
我期望的结果是:没有任何子项的记录列表,我的菜单表架构是: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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
建议
1-您不需要在第一次选择中选择匿名对象,您可以像
往常一样编写将集合命名为复数(
parentIDs
)的好习惯2-无需迭代来创建
new List<>
,这样您就可以在一个查询中写入所有内容答案:
首先选择所有叶级子 ID。获取除 ParentID 列中的值之外的所有 ID。然后通过加入 leafID 从菜单中进行选择
Suggestions
1-You don't need to select an anonymous object in the first select, you could write as
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 queryAnswer :
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