简体   繁体   English

使用HashSet删除基于T的属性不在另一个集合中的项目

[英]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. 我有2个包含不同对象的通用List集合。 I need list 1 to only include items whereby a property of that object is found in another list. 我需要列表1仅包括可以在另一个列表中找到该对象的属性的项目。

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. 我一直在研究HashSet<T>但是我不确定如何根据另一个列表的属性调用Remove。

How would I use a HashSet in my example to ensure that my second list only contains products that are within the first list? 我如何在示例中使用HashSet来确保第二个列表仅包含第一个列表中的产品?

You can probably just do the following, at least this way you aren't suffering a quadratic time complexity O(n*n) 您可能可以执行以下操作,至少这样就不会遇到二次时间复杂度O(n * n)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM