I am looking for a faster solution to the following problem.
I have three lists of products available in three different stores. I want to create a unique list containing all products available in the three stores and a unique list of products that appear in more than one store.
class Product{
public int Id;
//
public Product(int id)
{
this.Id = id;
}
}
List<Product> store1 = new List<Product>();
List<Product> store2 = new List<Product>();
List<Product> store3 = new List<Product>();
List<Product> allUniqueProducts = new List<Product>();
List<Product> moreThanOneStore= new List<Product>();
Fill the lists with some arbitrary values
for(int i=0;i<10000;i++){
store1.Add(new Product(i));
store2.Add(new Product(i+2000));
store3.Add(new Product(i+5000));
}
This is my solution however when the lists are large (in the region of 10,000) this code runs pretty slowly.
processStoreList(store1);
processStoreList(store2);
processStoreList(store3);
void processStoreList( List<Product> storeList ){
foreach ( Product pd in storeList ){
if ( !( allUniqueProducts.Count( x => x.Id == pd.Id ) > 0 ))
allUniqueProducts.Add(pd);
else if ( !( moreThanOneStore.Count( x => x.Id == pd.Id ) > 0 ))
moreThanOneStore.Add(pd);
}
}
Any suggestions?
You should use a
Dictionary<int, Product>instead ofList<Product>.This way,
ContainsKeywill be O(1) instead of O(n)