1

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.

1
  • 1
    Use following : (command[1] == "StartsWith")? x.StartsWith(command[2]) : (command[1] == "EndsWith") ? x.EndsWith(command[2]) : "Add Missing Value Here"; Commented Jun 1, 2020 at 13:09

2 Answers 2

6

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
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.