繁体   English   中英

C#使用条件执行代码? 方法调用:方法调用

[英]C# executing code using condition ? method call : method call

我正在尝试根据使用条件添加到一个列表或另一个列表中? : ? :语法,这在c#中可能吗,我使用的语法无法编译

List<int> Negatives = new List<int>();
List<int> Positives = new List<int>();

foreach (int number in numbers)
{
    (number >= 0) ? Negatives.Add(number) : Positives.Add(number);
}

条件运算符对一个表达式或其他表达式求值以计算值。 它不执行void返回方法。

不过,您可以在此处使用条件运算符来确定要添加到的列表:

(number >= 0 ? positives : negatives).Add(number);

或者更清楚地:

var listToAddTo = number >= 0 ? positives : negatives;
listToAddTo.Add(number);

当然,您也可以使用LINQ来取乐:

// This replaces the whole code
var lookup = numbers.ToLookup(x => x >= 0);
var positives = lookup[true].ToList();
var negatives = lookup[false].ToList();

甚至更严格地说:

var lookup = numbers.ToLookup(Math.Sign);
var positives = lookup[1].ToList();
var zeroes = lookup[0].ToList();
var negatives = lookup[-1].ToList();

条件表达式的结果和替代必须具有值; 无效返回方法没有任何价值。

使用if语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM