I am getting a list of products from my database as a BindingList. I would like to update the quantities some of the products in that list using another list of items already selected by the user.
The idea is when the user brings up a fresh list of products from the database. The list will show the quantities of products that have already been selected from a previous search.
I have come up with the following nested loop. It works but wouldn’t scale well as a search in the database could yield a large list that has to be traversed. How do you guys think I could improve this?
Also, I skimmed through the class where they taught the Big-O notation. What’s the complexity of the below solution?
Thanks.
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;
}
}
}
Your current approach with two nested loops is at best O(n^2) not counting the inner
ElementAtmethod calls. Use a dictionary instead to do this in O(n):