The other day while I was working on a side project I stumbled into the concept of using a reusable lambda expressions. I was querying data that in some cases needed to have a common filter run against it. So at first I realized I could do something like this:
Now this is pretty cool but moving forward with this concept I realized this could be a return value of a method that you may or may not pass parameters to. This would allow for a reusable conditional lambda expression. Example:
{
if (someVariable)
{
return x => x.Price > 100;
}
return x => x.Price < 100;
}
This opened many doors for me in regards to simplifying many methods. Now the one thing I did run into is you can only use this expression using the LINQ method syntax. For example this will work:
And this will not:
where ConditionalLambdaExpression(true)
select p;
Although if you prefer to use the syntax above you could do this:
where p.Name == "Test"
select p;
No comments:
Post a Comment