代码之家  ›  专栏  ›  技术社区  ›  Dice 249

在对象相交时快速设置属性?

  •  0
  • Dice 249  · 技术社区  · 7 年前

    当两个列表中都存在对象时,我在尝试设置属性时遇到性能问题

    public class Product
    {
        public int Id { get; set; }
    }
    
    public class DerivateProduct : Product
    {
        public bool isIntersected{ get; set; }
    }
    
    
    public class Storage
    {
        public Product stProduct { get; set; }
    }
    
    
    //Approx 10,000 objects
    ObservableCollection<DerivateProduct> Products;
    //Approx 500 Objects
    ObservableCollection<Storage> Storages;
    

    我使用以下代码,它可以工作,但性能很差(结果大约4秒)

    Products.Where(cp => Storages.Any(b => b.stProduct.Id == cp.Id))
                .ToList()
                .All(cp => cp.isIntersected = true);
    

    我尝试了以下方法,仅在150毫秒内就得到了正确的迭代次数,但我不知道如何设置 isIntersected=true 同时具有相同的性能。

    var intersectedId = Products.Select(cp => cp.Id)
                .Intersect(Storages.Select(b => b.stProduct.Id))
                .ToList();
    

    我真的需要帮助。所有答案将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  -2
  •   Dice 249    7 年前

    非常感谢@mjwills,5毫秒就可以了

    var stPrIds = Storages.Select(b => b.stProduct.Id).ToArray(); 
    foreach (var item in products.Where(cp => stPrIds .Contains(cp.Id)).ToList()) 
    { 
    item.IsBiocontrol = true; 
    }