【问题标题】:How can i write query record in table have parentID with condition parentID == 0 and ID != (parentID)我如何在表中写入查询记录有 parentID 条件 parentID == 0 和 ID!= (parentID)
【发布时间】:2011-03-31 18:12:50
【问题描述】:

我的 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。

【问题讨论】:

    标签: linq linq-to-sql


    【解决方案1】:

    建议

    1-第一次选择不需要选择匿名对象,可以写成

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

    将集合命名为复数 (parentIDs) 始终是一个好习惯

    2-无需迭代创建new List&lt;&gt;,因此您可以将它们全部写在一个查询中

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

    回答: 首先选择所有叶级子 ID。获取除 ParentID 列中的值之外的所有 ID。然后通过加入leafID从菜单中进行选择

    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 };
    

    【讨论】:

    • 我编辑了我的帖子,我期望的结果是:没有任何子项的记录列表,我的菜单表架构是:ID、名称、订单、ParentID。谢谢
    • 您好 nasmifive,我根据您的回答编写代码,但出现错误:在例外运算符为:System.collections.generic.IEnumberable 不包含“除外”的定义和最好的方法重载 'System.LINQ.queryable.Except(System.LINQ.IQueryalbe, System.collections.generic.IEnumberable)' 有一些无效的参数,我不知道如何解决它,你能给我一个建议吗?非常感谢
    • 另外,ID列Type是long
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2020-11-28
    相关资源
    最近更新 更多