Home > Software engineering >  Replace lambda with a function
Replace lambda with a function

Time:04-14

If I write this code, it works:

closestInPrice = list.OrderBy
                    (item => Math.Abs(2 * item.mid - price)).ToList();

If instead I try to replace the lambda with a function:

static double ComputeSpread(double mid, double price)
{
            return (2 * mid) - price;
}

Func<double, double, double> computeSpread = ComputeSpread;

closestInPrice = list.OrderBy(computeSpread).ToList();

it says the "type can't be inferred try explicitly":

CodePudding user response:

Part of your original lamba expression was accessing an object property, so you either need to explicitly pass that value when calling the function, or change the parameters of ComputeSpread to accept an item:

static double ComputeSpread(TClass item, double price)
{
    return (2 * item.mid) - price;
}

CodePudding user response:

You don't need computeSpread, but you do need to modify ComputeSpread to accept a single argument:

static double ComputeSpread(X item) //change X to whatever type is stored in your list
{
    return (2 * item.mid) - item.price;
}


closestInPrice = list.OrderBy(ComputeSpread).ToList();

You can also form your ComputeSpread like:

static double ComputeSpread(X item)  => (2 * item.mid) - item.price;

... would you do it? It depends how reusable you want ComputeSpread to be...

ps; If you put it in another class you might have to qualify it with a type and/or namespace name

closestInPrice = list.OrderBy(Helpers.ComputeSpread).ToList();

CodePudding user response:

You don't have to change the ComputeSpread helper method. Just define computeSpread as a new function:

Func<Item, double> computeSpread = item => ComputeSpread(item.mid, price);
var closestInPrice = list.OrderBy(computeSpread).ToList();

This assumes that price is a local variable that computeSpread can close over.

  • Related