简体   繁体   中英

Conditional Statement inside Lambda Expression c#

I'm trying to remove strings from List by given command. The command is to remove all strings that starts or ends with given string.

List input = new List() {"Pesho", "Misho", "Stefan"};

string command = "Remove StartsWith P"; or "Remove EndsWith P"

I'm trying to do it with lambda. Smth like this:

input.RemoveAll(x =>
{
if (command[1] == "StartsWith")
    x.StartsWith(command[2]);

else if (command[1] == "EndsWith")
    x.EndsWith(command[2]);
});

The compiler says: Not all code paths return a value in lambda expression of type Predicate

I'm asking is it possible to do it inside one lambda, or I have to write it for both cases.

The lambda syntax is a function. Without the {} braces the single line present implicitly returns its result, but with the braces you need an explicit return :

input.RemoveAll(x =>
{
    if (command[1] == "StartsWith")
        return x.StartsWith(command[2]);
    else if (command[1] == "EndsWith")
        return x.EndsWith(command[2]);
    else
        return false; // You'll need a default too
});

You can convert multiple if statements into one switch statement and use a return for every case label

input.RemoveAll(x =>
{
    switch (command[1])
    {
        case "StartsWith":
            return x.StartsWith(command[2]);
        case "EndsWith":
            return x.EndsWith(command[2]);
        default:
            return false;
    }
});

If you can target C# 8, it can be simplified using switch expression

input.RemoveAll(x =>
{
    return command[1] switch
    {
        "StartsWith" => x.StartsWith(command[2]),
        "EndsWith" => x.EndsWith(command[2]),
        _ => false
    };
});

But in both cases you should maintain a default case to return a false value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM