Search code examples
c#.netlambdafunc

Lambda expression to Func<T, TResult>


How can I write the lambda expression in optionObject.Forms.First(f => f.FormId == formId).MultipleIteration to a Func so at the end I have something like

Func<FormObject, bool> FormID = f => f.formID == passedVal;

and then use it on the first expression to get something like

optionObject.Forms.First(FormID).MultipleIteration

I tried

Func<FormObject, PassedVal, bool> FormID => formID == PassedVal;

but did not work.
Please note that there is nothing wrong with the lambda expression, it works fine. I am just trying to create a function to replace the expression with the name of the function to make the code look shorter and maintainable.


Solution

  • One option that lets you reuse the function body with new passed values is to generate Func<FormData, bool> instances in a class-level function:

    public static Func<FormObject, bool> CreateFormValidFunc(int validId)
    {
        return f => f.formID == validId;
    }
    

    Then you can use it like this:

    optionObject.Forms.First(CreateFormValidFunc(passedVal)).MultipleIteration
    optionObject.Forms.First(CreateFormValidFunc(2)).MultipleIteration
    

    An interesting side note is that int Foo => 0; is "expression-bodied properties" syntax (new to C# 6.0), and your attempt might have matched it just enough to make the error messages confusing.

    You can use expression-bodied methods to reduce the validation func generator to:

    public static Func<FormObject, bool> CreateFormValidFunc(int validId) => f => f.formID == validId;