Home > Enterprise >  How to use an if statement in a lambda function in C#
How to use an if statement in a lambda function in C#

Time:11-05

I am new in C#, I am not quite understand lambda, I want to convert this code to lambda expression

private static bool my_method(int i)
{
    if(i == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

I want to convert this code to lambda expression, Thank

CodePudding user response:

Your code, made legal with a function name, looks like this:

private static bool SomeFunction(int i)
{
    if (i == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

That can get rewritten as this:

private static bool SomeFunction(int i)
{
    return i == 0;
}

Which can, in turn, be rewritten as this:

private static bool SomeFunction(int i) => i == 0;

And that, can get rewritten, as a Func<int, bool> lambda, as this:

Func<int, bool> someFunction = i => i == 0;

CodePudding user response:

There already is an answer to this but I want to include more details.

If you have a function such as

bool MyMethod(int i)
{
    ...//Method body
}

and you want to change it as a lambda expression, you can make use of the Func<ReturnType, Parmeter1, Parameter2, ...> delegate with MyMethod() defined before as:

using System;

Func<int, bool> myLabmdaExp = (i) => MyMethod(i); //Here it is implied that i is an int

or you could define the expression in braces {} such as:

using System;

Func<int, bool> myLabmdaExp = (i) => 
{
    ....//Function body
}

In your case,

Func<int, bool> func = (val) =>
{
    if(i==0)
    {
        return true;
    }
    else
    {
        return false;
    }

}

You can use a bit of boolean logic to reduce your lamda expression as

Func<int, bool> func = (val) => val==0;

CodePudding user response:

Func<int, bool> func = (i) => {
    if (i == 0) return true;
    else return false;
};
  • Related