C# executing code using condition ? method call : method call

I'm trying to add to one list or another based on a condition using ? : syntax, is this possible in c#, the syntax I was using does not compile

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);
}
Jon Skeet
people
quotationmark

The conditional operator evaluates one expression or other to compute a value. It doesn't execute void-returning methods.

You can use the conditional operator here though, to decide which list to add to:

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

Or more clearly:

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

Of course, you could use LINQ instead, for fun:

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

Or even, to be more strictly-accurate:

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

people

See more on this question at Stackoverflow