xaria
xaria

Reputation: 842

Remove items from collection using linq

I have a query which works as expected. If mastercollection does not a corresponding AssocaitedProp which exists in MyCollection then remove that item from MyCollection

public class classB
{
    public classX AssociatedProp { get; set; }
}

    List<classX> MyCollection;
    List<classB> masterCollection;

    MyCollection.RemoveAll(x =>
                    MyCollection.Except(
                     (from n in masterCollection
                      select n.AssociatedProp).Distinct()).ToList().Contains(x)
                     );

This query will remove all the items from MyCollection which are not in masterCollection.

Now I have modified MyCollection as collection of classC

public class classC
{
    bool flag { get; set; }
    classX myObj { get; set; }
}

List<classC> myCollection;
List<classB> masterCollection;

and List MyCollection

How can I achieve the same results. That is to remove all items from MyCollection if masterCollection does not have any item with ClassX value existing in MyCollection

I know the explanation is not clear enough.

Upvotes: 2

Views: 5250

Answers (1)

Aron
Aron

Reputation: 15772

var toKeep = new HashSet(masterCollection.Select(x => x.AssociatedProp));

foreach(var x in myCollection.Where(i => toKeep.Contains(i.myObj) == false).ToList())
{
    myCollection.Remove(x);
}

You want to bring the Search list outside of the lambda, else you recreate it each item. You also want a HashSet, as they are the fastest collection for searching in.

Upvotes: 3

Related Questions