Reputation: 278
I have two lists:
Two seperate results of sql queries.
The second list has a 'ProductId'.
What I'm currently doing is:
foreach(var product in Products)
var productWarehouses = Warehouses.Where(x=> x.ProductId == productId).ToList();
product.Warehouses = productWarehouses;
Thing is, this takes very, very long.
Note: I've tried splitting Products into chunks of lists and using Parallel.Foreach() and Tasks to take the time down - but still takes very long.
Upvotes: 0
Views: 58
Reputation: 12670
Create a Dictionary<int, Product>
from your Products
where Product.ProductID
is used as key:
var pd = Products.ToDictionary(p => p.ProductID, p => p);
then you can iterate over Warehouses and lookup appropriate products fast:
foreach (var wh in Warehouses)
{
pd[wh.ProductId].Warehouses.Add(wh); //supposed Product.Warehouses lists have already been created, if not, add checks and create them as needed.
}
Upvotes: 0
Reputation: 203830
Use a Join
rather than doing a linear search through the entirety of one collection for each item in the other collection:
var query = from product in Products
join warehouse in Warehouses
on product.productId equals warehouse.ProductId
into warehouses
select new
{
product,
warehouses,
};
Upvotes: 1
Reputation: 393
Instead of doing this in c#, I would prefer to do it in SQL stored procedure. Get all details from one sql and then iterate though result to create Product list.
Upvotes: 0