Lock
Lock

Reputation: 5522

Using HashSet to remove items not in another collection based on a property of T

I have 2 generic List collections which contain different objects. I need list 1 to only include items whereby a property of that object is found in another list.

Currently, I am achieving that like this:

foreach (var product in navCat.Value.CategoryAssignment.ToArray())
{
    if (!masterCatalog.Product.Any(p => p.ProductId == product.ProductId))
    {
        //this product doesn't exist in the master catalog so lets remove it
        navCat.Value.CategoryAssignment.RemoveAll(p => p.ProductId == product.ProductId);
    }
} 

This works well... but it is very slow! What would a more efficient way be? I have been looking into HashSet<T> but I'm not sure how to call Remove based on the property of another list.

How would I use a HashSet in my example to ensure that my second list only contains products that are within the first list?

Upvotes: 1

Views: 561

Answers (1)

TheGeneral
TheGeneral

Reputation: 81503

You can probably just do the following, at least this way you aren't suffering a quadratic time complexity O(n*n)

var masterIds = masterCatalog.Product.Select(x => x.ProductId).ToList();

navCat.Value.CategoryAssignment.RemoveAll(x => !masterIds.Contains(x.ProductId));

Upvotes: 3

Related Questions