C # Action <T>, Pass function as parameter

I want to pass the condition as an action to another method. The first line in "ComputerPriceGenerator" works, but how to make the array work (second line)? .. Any ideas

I am looking for advice ..., CalculateAllPrice has not been developed 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;
}
+3
source share
3 answers

Your method CalculatePriceshould not accept only Action, IMO - both methods should accept Action<Computer>. Therefore, I would have such methods:

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

and name them as follows:

PriceMachine.CalculatePrice(cart.Computers[0], ComputerConverter);
PriceMachine.CalculateAllPrice(cart.Computers, ComputerConverter);
+10
source

As you want to apply a method to all elements of an array, you cannot bypass its iteration.

You can define PriceMachine.CalculateAllPriceas such:

public void CalculateAllPrice(IEnumerable<Computer> data, Action<Computer> action)
{
  foreach(Computer c in data)
    action(c);
}
+1
source
PriceMachine.CalculateAllPrice(cart.Computers, (Computer x) => ComputerConverter(x));

CalculateAllPrice cart.Computers .

+1

Source: https://habr.com/ru/post/1789122/


All Articles