簡體   English   中英

Lambda 表達式中的條件語句 c#

[英]Conditional Statement inside Lambda Expression c#

我正在嘗試通過給定命令從列表中刪除字符串。 該命令是刪除所有以給定字符串開頭或結尾的字符串。

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

string command = "刪除 StartsWith P"; 或“刪除以 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 中做到這一點,或者我必須為這兩種情況編寫它。

lambda 語法是 function。 如果沒有{}大括號,存在的單行將隱式返回其結果,但使用大括號,您需要顯式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
});

您可以將多個if語句轉換為一個switch語句,並為每種case使用一個return label

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表達式進行簡化

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

但是在這兩種情況下,您都應該保持default情況以返回false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM