我可以用lambda缩短if/else语句吗
本文关键字:else 语句 if lambda 缩短 我可以 | 更新日期: 2023-09-27 18:27:37
作为为数据表构建数据行的一部分,我有以下语句,我想知道是否可以使用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;
}
}
您想要?运算符,您不需要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";
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
是很重要的,因为?:
三元运算符需要返回结果,true大小写和false大小写都必须隐式转换为其他大小写。我不知道accrued_interest
的类型是什么,我假设它将是double
或decimal
,因为decimal
和DBNull
之间没有隐式转换。为了使其工作,您必须转换为object
类型。清楚吗?
您不需要调用单独的方法。无需方法或任何其他东西
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);
}