Skip to main content
 首页 » 编程设计

c#之用于更新集合的嵌套循环的替代方法

2024年02月23日30lyhabc

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

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

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

此外,我还浏览了他们教授大 O 符号的类(class)。以下解决方案的复杂性如何?

谢谢。

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; 
        } 
    } 
} 

请您参考如下方法:

您当前使用两个嵌套循环的方法充其量是 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]; 
}