【问题标题】:Quickly set property when objects are intersected?对象相交时快速设置属性?
【发布时间】:2018-04-17 12:32:23
【问题描述】:

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

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();

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

【问题讨论】:

  • 你的英语不像大多数海报那么差,别担心;)
  • @MongZhu 不,这是我在简化代码时犯的一个错误,我将其删除。它没有隐藏
  • @LonelyNeuron 谢谢 :)
  • 集合是使用 Nhibernate 创建的,询问数据库大约需要 4 秒,但在执行 Where()..All() 查询时又需要 4 秒
  • @MongZhu 谢谢你的猜测,我已经进一步调查了。执行代码时似乎没有进行 Db 或 Orm 调用(已经清理了调试输出,没有任何结果。根据您的猜测,我已经删除了 ToList 没有必要,但执行时间仍然约为 4 秒 :( 谢谢很多你的帮助

标签: c# performance linq observablecollection


【解决方案1】:

非常感谢@mjwills,它只需 5ms 就可以正常工作

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

【讨论】:

  • 这不是我的建议。我建议使用HashSet
猜你喜欢
  • 1970-01-01
  • 2020-03-31
  • 2015-11-24
  • 2021-06-07
  • 2017-01-07
  • 2015-06-23
  • 1970-01-01
  • 2018-12-02
  • 2013-04-11
相关资源
最近更新 更多