C# 我可以用 lambda 缩短 if/else 语句吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18236672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I shorten an if/else statement with lambda?
提问by vwdewaal
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;
}
}
采纳答案by Sriram Sakthivel
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. 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
. In order to make it work you've to cast to object
type.
Is that clear?
编辑:转换为object
很重要,因为?:
三元运算符需要返回结果,true case 和 false case 必须隐式转换为 other。我不知道什么是类型,accrued_interest
我认为它将是 adouble
或者decimal
因为decimal
和之间没有隐式转换DBNull
。为了使其工作,您必须强制转换为object
类型。明白了吗?
回答by Ehsan
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;
回答by Zac
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";
回答by Blank
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);
}