Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Action<T>, Pass function as parameter

Tags:

c#

I want to pass a condition as Action to another method. First line in "ComputerPriceGenerator" works, but how to make the array work (second line)?.. Any ideas

I'm looking for advice..., CalculateAllPrice is not designed yet

public void ComputerPriceGenerator()
{
    //Below line Works
    PriceMachine.CalculatePrice(cart.Computers[0],() => ComputerConverter(cart.Computers[0]));           
    //How to make this work, i don't want to loop it???
    PriceMachine.CalculateAllPrice(cart.Computers,() => ComputerConverter(??));
}

public void ComputerConverter(Computer comp)
{
    if (comp.Memory <= 2)
        comp.Discount = 10;
}
like image 791
kayak Avatar asked Apr 15 '26 10:04

kayak


2 Answers

Your CalculatePrice method shouldn't take just Action, IMO - both methods should take Action<Computer>. So I would have the methods like this:

public static void CalculatePrice(Computer computer, Action<Computer> action)
public static void CalcuateAllPrices(IEnumerable<Computer> computers,
                                     Action<Computer> action)

and call them like this:

PriceMachine.CalculatePrice(cart.Computers[0], ComputerConverter);
PriceMachine.CalculateAllPrice(cart.Computers, ComputerConverter);
like image 196
Jon Skeet Avatar answered Apr 17 '26 22:04

Jon Skeet


As you want to apply the method to all elements of the array, you won't get around iterating over it.

You could define PriceMachine.CalculateAllPrice as such:

public void CalculateAllPrice(IEnumerable<Computer> data, Action<Computer> action)
{
  foreach(Computer c in data)
    action(c);
}
like image 33
Femaref Avatar answered Apr 17 '26 23:04

Femaref



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!