Currently i am creating an extension method that accepts parameters. Using the below example, how could one convert this using lambda expressions?
public static decimal ChangePercentage(this IEnumerable<Trade> trades, DateTime startDate, DateTime endDate)
{
var query = from trade in trades
where trade.TradeTime >= startDate
where trade.TradeTime <= endDate
orderby trade.TradeTime descending
select trade;
return (query.First().Value - query.Last().Value) / query.First().Value * 100;
}
What are the pro/cons using lambda vs normal method parameters?
Thanks
Did you want to replace the
startDate
andendDate
parameters with a single lambda expression?Your method is implicitly using lambda expressions already.
When you say
What you're really saying is "given a
Trade
called "trade
", return abool
by evaluating the following:trade.TradeTime >= startDate
."That is the definition of this lambda expression:
And in fact, minus the declaration of
expr
, this is how you would express it if you were using the function composition syntax for LINQ instead of the query syntax.One way you could change the sample to use lambda expressions is to use a filter.
The biggest pro this gives you is flexbility. Instead of having a method which does date based filtering for calculation. You have a method with a flexible filter method for calculating percentages.
Continuing on Tim's answer, you could also provide a lambda to perform the calculation:
Usage:
It's important to understand that Lambda expressions serve a different purpose than extension methods. Lambda expressions are used primarily as a compact syntax for defining a delegate implementation or function implementaion. An added benefit of lambda expressions is that you can define event handlers and functions within the body of another function, useful if you have a simple function that is used only within a specific method. Just define the function using the Func<> or Action<> type with lamda syntax.
I would recommend picking up a copy of Jon Skeet's C# In Depth. It covers these topics in detail.
Here's this function as a lambda expression
If you don't want parameters, you can move the filtering outside.
Then, it can be called like this: