Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a Func without Lambde expression?

I am just thinking how to convert this: List.Where(X=>X>5); to non-lambda expression code. I cannot figure out how to get Func working here.

like image 548
John V Avatar asked Dec 06 '22 07:12

John V


2 Answers

There are two reasonably simple possibilities for creating delegates without using lambda expressions:

  • Write a method and use a method group conversion

    private static bool GreaterThan5(int x)
    {
        return x > 5;
    }
    
    ...
    
    var query = list.Where(GreaterThan5);
    
  • Use an anonymous method

    var query = list.Where(delegate(int x) { return x > 5; });
    

Neither of those are as clear as using a lambda expression though. For more complicated examples where you actually want to capture local variables, the "write a separate method" version would get a lot more complicated.

like image 165
Jon Skeet Avatar answered Dec 09 '22 15:12

Jon Skeet


While I don't understand the purpose of this, you can do it like this:

bool MyFilterFunction(int x)
{
    return x > 5;
}

Then rewrite your code:

List.Where(MyFilterFunction);
like image 45
Sasha Avatar answered Dec 09 '22 14:12

Sasha