【问题标题】:Conditional Statement inside Lambda Expression c#Lambda 表达式 c# 中的条件语句
【发布时间】:2020-06-15 04:35:57
【问题描述】:

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

列表输入 = new List() {"Pesho", "Misho", "Stefan"};

string command = "删除 StartsWith P";或“删除 EndsWith P”

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

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

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

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

我在问是否有可能在一个 lambda 中做到这一点, 或者我必须为这两种情况都写。

【问题讨论】:

  • 使用以下 : (command[1] == "StartsWith")? x.StartsWith(command[2]) : (command[1] == "EndsWith") ? x.EndsWith(command[2]) : "在此处添加缺失值";

标签: c# lambda


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多