I am trying to re-write the following using LINQ
foreach (WMCommon.Services.StakeOut.assembly ass in assemblies)
{
foreach (var agg in aggregate)
{
I am hoping that the LINQ will be much faster than nested FOREACH?
In general, LINQ isn't going to improve your performance unless you change how it works. LINQ is effectively just performing the iterations for you.
In this case, it appears you could just use a join to improve this overall, as this is going to give you the same effect:
var query = from WMCommon.Services.StakeOut.assembly ass in assemblies
join agg in aggregate
on new { ass.unitActn, ass.unitCode, ass.unitLength } equals new { (agg.catagory.unitActn, agg.catagory.unitCode, agg.catagory.unitLength }
select new { ass, agg };
foreach(var pair in query)
pair.ass.quantity = pair.agg.qty;
Try this:
assemblies.ForEach(a => a.quantity = (aggregate.Where(p => p.catagory.unitActn == a.unitActn && p.catagory.unitCode == a.unitCode && p.catagory.unitLength == a.unitLength).Select(s=>s.qty)));
But mind it it wouldn't be faster
Why Linq? it's unlikely to be any faster than what you've got. It's unlikely to be any simpler or easier to read or easier to debug than what you've got.
If you're looking to improve performance, Your nested loops run on O(mn) time, where m is the size of the assemblies collection and n is the size of the aggregates collection, so basically O(n2) time.
Are the collections orderd by the key values? If so, merging the two collections by iterating over the two in lockstep will be a big win. That should bring you down to something like O(n) performance.
If they are not ordered, you can get a win by taking the aggregates collection and converting it into a lookup table like a Dictionary, prior to iterating over the assemblies collection. Then its a straight iteration over assemblies with a presumably fast lookup against the dictionary.