1

My VS2010 using ReSharper which prompts to converts foreach to LINQ. It converts from

foreach (var item in quotePrice.ExtraServiceBreakdown)
{
    hazmatRate = (quoteRequest.IsHazMat && item.Id == VitranHazmatCode) ?   
                                                 item.Cost : hazmatRate;
}

to

hazmatRate = quotePrice.ExtraServiceBreakdown.Aggregate(
                 hazmatRate, (current, item) => 
                     (quoteRequest.IsHazMat && item.Id == VitranHazmatCode) ? 
                         item.Cost : current);

I have two questions here,

  1. What does current meant? Is that points to the variable hazmatRate?
  2. What does Aggregate actually does?
J. Steen
  • 15,470
  • 15
  • 56
  • 63
Hary
  • 5,690
  • 7
  • 42
  • 79
  • 1
    The problem is that you're setting a variable in a `foreach` without breaking it, hence your always overwriting it. This is not efficient and possibly error-prone(if you don't want the last value). – Tim Schmelter Feb 07 '13 at 09:26
  • On question #2, have you tried reading the documentation on Aggregate? – John Saunders Feb 07 '13 at 09:29
  • @TimSchmelter, can u explain a bit more with this? **without breaking it,** – Hary Feb 07 '13 at 09:33
  • 2
    @DON: You can `break` a loop when you've found what you were looking for. So assuming that you actually want to find the first item with with `id=VitranHazmatCode`, you should exit the `foreach` via `break;`. If you want to sum a number instead, you'll need to use `hazmatRate += ...` instead. – Tim Schmelter Feb 07 '13 at 09:35
  • In that case also use a different Hazmat rate in the foreach loop then the one you will be increasing. – JMan Feb 07 '13 at 09:38
  • @TimSchmelter yes i can understand that now and i will do that thanks – Hary Feb 07 '13 at 09:41
  • @JeroenMoonen, sorry i cant understand? can u explain it pls? – Hary Feb 07 '13 at 09:42
  • @JeroenMoonen, yeah i can now understood and here in my case i wont need that – Hary Feb 07 '13 at 09:44

1 Answers1

1
  1. Current indeed point to your Hazmat
  2. LINQ Aggregate algorithm explained

And i think you will need to do as stated in the comment by Tim:

    hazmatRate += (quoteRequest.IsHazMat && item.Id == VitranHazmatCode) ?   item.Cost : hazmatRate;

But in this case i'd change 'hazmatRate' by a base rate declared before your function. Otherwise you would be increasing your value with the value it contained before making it grow exponentially

Community
  • 1
  • 1
JMan
  • 2,611
  • 3
  • 30
  • 51