Search code examples
c#linqiteratoraggregate

Iterator in aggregate (linq)?


Lets say I have a small integer array like this:

{10,20,30}

Now for the items of that array I want to apply the following formula:

10^(arrayLenght-1) + 20^{arrayLenght-2) + 30^{arrayLenght-3}

Is there a way to accompish this by using the linq aggregate methode though you need some kind of an iterator, which aggregate doesnt implement when I see this right?


Solution

  • Here's how I would do it:

    array.Select((num, index) => Math.Pow(num, items.Length - index - 1)).Sum();