Pentester Penguin
Pentester Penguin

Reputation: 41

Using the ternary operator with a lambda expression inside a foreach in C#

I'm trying to lear how to properly use lambda expressions in C# and I got into this problem. I have an array of booleans defined like this:

public bool[] worldState = new bool[25];

Now, after giving values to it, I want to cycle thorugh it and simply print "T" when the bool is true, and "F" when it's false. I know how to do it with loops, but I wanted to do it with a one-liner, so I came up with this:

Array.ForEach(worldState, x => x? Console.WriteLine("T"): Console.WriteLine("F") );

This, however, won't work. Why? What's the correct way to do this?

Upvotes: 1

Views: 2727

Answers (3)

Trisped
Trisped

Reputation: 6003

Try:

Array.ForEach(worldState, x =>  Console.WriteLine(x ? "T" : "F") );

The ternary function requires a value be returned, so in this case your T or F should be returned to the WriteLine method.

Personally, I think a foreach or for loop would be cleaner and more efficient.

foreach(bool bVal in Array) { Console.WriteLine(bVal ? "T" : "F"); }

or

for(i = 0; i < Array.Length; i ++) { Console.WriteLine(Array[i] ? "T" : "F"); }

Upvotes: 4

D Stanley
D Stanley

Reputation: 152521

The proper syntax for an if-else in ForEach would be:

Array.ForEach(worldState, x => { if(x) { Console.WriteLine("T"); } else { Console.WriteLine("F");}} );

The ternary operator ? : requires expressions that return compatible values as the arguments. Console.WriteLine is a void function and does not return a value.

Although I would note that a standard foreach loop is much easier to read and debug. I would not recommend using .ForEach() for this type of operation. In fact I wouldn't recommend it for any operation since it doesn't add any capability over the standard loop.

Upvotes: 1

clcto
clcto

Reputation: 9648

It's because Console.WriteLine() doesn't return anything. From the Ternary operator documentation, emphasis mine:

The conditional operator (?:) returns one of two values

and Console.WriteLine() does not return a value.

Just use an if statement:

Array.ForEach(worldState, x => { if(x) Console.WriteLine("T"); else Console.WriteLine("F"); } );

Another possibility is just return the string you want using the ternary operator:

Array.ForEach(worldState, x => Console.WriteLine( x ? "T" : "F" ) );

Upvotes: 1

Related Questions