5

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.

Yoismel
  • 115
  • 1
  • 10
  • 4
    not following, can you explain your question in more detail? – Xiaomin Wu Dec 31 '15 at 20:18
  • 1
    Possible duplicate of [Reuse of a LINQ query](http://stackoverflow.com/questions/34337294/reuse-of-a-linq-query) – Hamid Pourjam Dec 31 '15 at 20:21
  • Yes, this is just like Reuse of a LINQ link above, just that in this case the value to compare with is not hard coded, but a parameter passed to the method where the expression is used – Yoismel Dec 31 '15 at 22:15
  • The reason your `Func` didn't work is that the signature of the lambda taken by `First` and similar methods would need to be `Func`. Since you have another value that you also want to parameterize, 31eee384's answer looks like the best and possibly the only way to do it. – Ann L. Dec 31 '15 at 22:22

2 Answers2

3

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;
31eee384
  • 2,748
  • 2
  • 18
  • 27
0

This post can help you: lambda expression and var keyword

When I try to use var add = (x, y) => x + y; the compiler need to be able to reduce the set to just one type for x and one for y (not exactly true, it might be that both a base class and a derived class would fit) and still even if the compiler could figure out the type for x and y or that you specified the types to let's say int you'd still be left with the fact that both Expression> and Func are possible types for add.

In your scenario you can use this:

Expression<Func<FormObject, bool>> FormID = f => f.formID == passedVal;
Community
  • 1
  • 1
Fred
  • 3,365
  • 4
  • 36
  • 57