CompanyDroneFromSector7G
CompanyDroneFromSector7G

Reputation: 4527

Remove parents from list

I have 2 lists, both containing objects which look like this: (this is a simplification)

class ddItem
{
    public string Code;
    public string Key;
    public string ParentKey;
}

One list contains items which may or may not have children in the other list. I'm trying to figure out a nice way to remove items from the parent list if they have a corresponding item in the child list, i.e. where parent.Key = child.parentKey.

This is the LINQ I have, and it's currently causing me to lose brain cells:

parentList = 
    (List<ddItem>)parentList.Where(p => childList.Select(c => c.ParentKey == p.Key));

Currently I have a red squiggly line under childList.Select(c => c.ParentKey == p.Key) and the message Cannot convert expression type 'System.Collections.Generic.IEnumerable<bool>' to return type 'bool' so I must be missing a cast somewhere - I think...

[EDIT]

For posterity, the correct code is:

parentList = 
    parentList.Where(p => childList.Any(c => c.ParentKey == p.Key)).ToList();

(I also had to move the cast)

[/EDIT]

Upvotes: 0

Views: 74

Answers (1)

Magnus
Magnus

Reputation: 46997

I think you need only to change from select to any in the where

parentList.Where(p => childtList.Any(c => c.ParentKey == p.Key))

Upvotes: 5

Related Questions