简体   繁体   English

我可以用lambda缩短if / else语句吗?

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

I have the following statement as part of building a datarow for a datatable and I was wondering if I could shorten it using a lambda statement or anything more elegant. 作为构建数据表的数据行的一部分,我有以下语句,我想知道是否可以使用lambda语句或更优雅的方法来缩短它。

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

The statement is checked by: 该语句由以下人员检查:

 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;

Edit: casting to object is important since ?: ternary operator needs to return results both true case and false case has to be implicitly converted to other. 编辑:强制转换为object很重要,因为?:三元运算符需要返回结果,必须将真值和假值都隐式转换为其他值。 I don't know what is type of accrued_interest I assume it will be a double or decimal since there is no implicit conversion between decimal and DBNull . 我不知道accrued_interest类型是什么,我认为它将是double accrued_interestdecimal因为在decimalDBNull之间没有隐式转换。 In order to make it work you've to cast to object type. 为了使其工作,必须将其强制转换为object类型。 Is that clear? 明白了吗?

You want the ? 你要吗? Operator, you don't need a lambda expression. 运算符,您不需要lambda表达式。

http://msdn.microsoft.com/en-us/library/ty67wk28.aspx 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";

You don't need to call a separate method. 您无需调用单独的方法。 No need of method or any other things 无需方法或其他任何东西

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

Also, 也,

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

To.. 至..

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