开发者

How to fix this LINQ Error

开发者 https://www.devze.com 2023-02-21 05:13 出处:网络
The Result as i expect here is : list of record that do not have any children, my Menu table schema is : ID (long), Name(string), Order(int), ParentID (long)

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

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

here my code :

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


this.ddlMenu.DataSource = from m in menus
              开发者_StackOverflow         join id in leafMenuIDs on m.ID equals id
                       select new { m.ID, m.Name };

i got a error : at Except operator is :

System.collections.generic.IEnumberable<long> does not contains a definition for 'Except' and the best method overload System.LINQ.queryable.Except<TSource>(System.LINQ.IQueryalbe<TSource>, System.collections.generic.IEnumberable<Tsource>) has some invalid arguments .

please help me fix this error. thanks a lot


What about something like:

var items = from m in menus
            where !menus.Where(c => c.ParentID == m.ID).Any() 
            select new { 
                m.ID,
                m.Name};

Here you are selected every menu that doesn't have a ParentID referring back to it.


In response to comment by @mmix, here's the generated SQL (using Linqpad)

SELECT [t0].[ID], [t0].[Name]
FROM [menus] AS [t0]
WHERE NOT (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [menus] AS [t1]
    WHERE [t1].[ParentID] = ([t0].[ID])
    ))


I think the problem here might be that m=>m.ID & m=>m.ParentID are conflicting. Try changing it to m=>m.ID and x=>x.ParentID (different lambda expression names)

0

精彩评论

暂无评论...
验证码 换一张
取 消