NevenHuynh
NevenHuynh

Reputation: 33

How to fix this LINQ Error

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

Upvotes: 1

Views: 162

Answers (2)

Michiel Cornille
Michiel Cornille

Reputation: 2097

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)

Upvotes: 0

Geoff Appleford
Geoff Appleford

Reputation: 18832

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])
    ))

Upvotes: 2

Related Questions