4

I am pretty new to C# and as a practice exercise was trying to convert a console input of Y's and N's into boolean array of true and false (Y=true N=false).

enter image description here

I get the "Only assignment call, increment, decrement, await and new object expressions can be used as a statement" error. Any suggestions?

4 Answers 4

3

Try:

bool[] tempArray = Console.ReadLine().ToList().ConvertAll(ch => Char.Equals(ch, 'Y')).ToArray();

Lambdas do not need the type of their parameters to be specified in the declaration, they are inferred automatically. You would also need to convert to the list of bools to an array with ToArray.

Sign up to request clarification or add additional context in comments.

1 Comment

Something else that is inferred automatically: generic type arguments. You don't need either the <char> or <bool> here.
1

This works and is a bit simpler.

var array = Console.ReadLine().Select(x => x == 'y');

I believe it is because you are working with a list and an array. That was the error I got when trying your method.

2 Comments

Nope, that will be IEnumerable<bool>. Also you don't need ToArray<char> for string.
So keep the var and add ToArray(). But why bother when 99/100 times an IEnumerable will do the trick? I mean it is a LINQ question after all.
1
bool[] tempArray = Console.ReadLine().Select(ch => ch == 'Y').ToArray();

1 Comment

Just curious, why a byte array?
0

To make it error-free:

var bools = Console.ReadLine().Where(x => Char.ToUpperInvariant(x) == 'Y' || Char.ToUpperInvariant(x) == 'N').Select(x => x == 'Y');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.