Lambda表达式C#中的条件语句

时间:2020-06-01 13:04:28

标签: c# lambda

我正在尝试通过给定命令从列表中删除字符串。 该命令将删除以给定字符串开头或结尾的所有字符串。

列表输入=新的List(){“ Pesho”,“ Misho”,“ Stefan”};

string command =“ Remove StartsWith P”;或“删除带有P的结尾”

我正在尝试使用lambda。像这样:

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

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

编译器说: 并非所有的代码路径都在Lambda表达式中返回Predicate类型的值

我问是否可以在一个lambda内进行操作, 或者我必须为两种情况都写它。

2 个答案:

答案 0 :(得分:6)

lambda语法是一个函数。如果没有{}括号,则显示的单行会隐式返回其结果,但是括号则需要显式的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
});

答案 1 :(得分:2)

您可以将多个if语句转换为一个switch语句,并为每个return标签使用case

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

如果您可以定位C#8,则可以使用switch expression

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

但是在两种情况下,您都应维持一个default的情况以返回一个false的值

相关问题