簡體   English   中英

我可以用lambda縮短if / else語句嗎?

[英]Can I shorten an if/else statement with lambda?

作為構建數據表的數據行的一部分,我有以下語句,我想知道是否可以使用lambda語句或更優雅的方法來縮短它。

if (outval(line.accrued_interest.ToString()) == true) 
{ 
temprow["AccruedInterest"] = line.accrued_interest; 
} 
else 
{
temprow["AccruedInterest"] = DBNull.Value;
}

該語句由以下人員檢查:

 public static bool outval(string value)
        {
            decimal outvalue;
            bool suc = decimal.TryParse(value, out outvalue);
            if (suc)
            {
                return true;
            }
            else
            {
                return false;
            }


        }
public static bool outval(string value)
{
    decimal outvalue;
    return decimal.TryParse(value, out outvalue);
}

temprow["AccruedInterest"] = outval(line.accrued_interest.ToString()) ? (object)line.accrued_interest : (object)DBNull.Value;

編輯:強制轉換為object很重要,因為?:三元運算符需要返回結果,必須將真值和假值都隱式轉換為其他值。 我不知道accrued_interest類型是什么,我認為它將是double accrued_interestdecimal因為在decimalDBNull之間沒有隱式轉換。 為了使其工作,必須將其強制轉換為object類型。 明白了嗎?

你要嗎? 運算符,您不需要lambda表達式。

http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

int input = Convert.ToInt32(Console.ReadLine());
string classify;

// if-else construction.
if (input < 0)
    classify = "negative";
else
    classify = "positive";

// ?: conditional operator.
classify = (input < 0) ? "negative" : "positive";

您無需調用單獨的方法。 無需方法或其他任何東西

decimal result;   
if(decimal.TryParse(line.accrued_interest.ToString(),out result))
 temprow["AccruedInterest"] = line.accrued_interest
else
 temprow["AccruedInterest"] = DBNull.Value; 

也,

public static bool outval(string value)
{
    decimal outvalue;
    bool suc = decimal.TryParse(value, out outvalue);
    if (suc)
    {
        return true;
    }
    else
    {
        return false;
    }
}

至..

public static bool outval(string value)
{
    decimal outvalue;
    return decimal.TryParse(value, out outvalue);
}

暫無
暫無

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

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