替代嵌套循环以更新集合

时间:2012-03-22 17:49:21

标签: c# .net big-o bindinglist

我从我的数据库中获取一个产品列表作为BindingList。我想使用用户已选择的另一个项目列表来更新该列表中某些产品的数量。

这个想法是用户从数据库中提取新的产品列表。该列表将显示已从先前搜索中选择的产品数量。

我提出了以下嵌套循环。它工作但不能很好地扩展,因为数据库中的搜索可能会产生一个必须遍历的大型列表。你们怎么认为我可以改善这个?

另外,我浏览了他们教授Big-O符号的课程。以下解决方案的复杂性是什么?

感谢。

for (int i = 0; i < dbProducts.Count; i++ )
{
    for (int j = 0; j < GlobalVars.productList.Count; j++)
    {
        EposProduct selectedProduct = GlobalVars.productList.ElementAt(j);
        EposProduct dbProduct = dbProducts.ElementAt(i);
        if(selectedProduct.ProductID == dbProduct.ProductID)
        {
            dbProduct.Quantity = selectedProduct.Quantity;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

当前使用两个嵌套循环的方法最多只计算O(n ^ 2)内部ElementAt方法调用。使用字典代替在O(n)中执行此操作:

var gbMap = GlobalVars.productList.ToDictionary(x => x.ProductId, 
                                                x => x.Quantity); 
foreach(var product in dbProducts)
{
    if(gbMap.ContainsKey(product.ProductId))
        product.Quantity = gbMap[product.ProductId];
}
相关问题