1

I want to "save" my output from my foreach loop into a boolean array. What would be the easiest way to tackle that?

foreach(char est in resultss)
{
    
    int test = est - '0';
    tru = Convert.ToBoolean(test); // A Bool[] instead of Bool
    //  Console.WriteLine(tru);
}

I'm working on a binary clock and imp trying to convert a number like 22 into binary (done that) and than into a bool array.

3
  • 3
    Help us help you - share some sample data and the result you'd like to get for it. Commented Aug 21, 2020 at 16:20
  • 1
    var theArray = resultss.Select(x => Convert.ToBoolean(x - '0')).ToArray(); Commented Aug 21, 2020 at 16:23
  • I will try that out, Thank u! Commented Aug 21, 2020 at 16:32

2 Answers 2

1
 List<bool> list = new List<bool>();
 foreach(char est in resultss)
 {
     int test = est - '0';
     tru = Convert.ToBoolean(test);
     list.Add(tru);
 }
Sign up to request clarification or add additional context in comments.

4 Comments

That's.. Perfect! Thank u a lot!
It should be list.Add(tru); C# is case sensitive...
@uk3ndt please make sure not to use that - there is rarely a good reason to use Convert. and definitely in this case Convert.ToBoolean is wrong method to use. If OP wanted to check est being '0' or not they should have simply compare it like list.Add(est != '0').
Thanks for the notice, i changed it like u said :))
1

You could use LINQ for this, please add reference to System.Linq and do this.

var boolArray = resultss.Select(r => Convert.ToBoolean(r - '0')).ToArray();

5 Comments

The second code sample is great, but what does the first code block have to do with this question?
Actually Convert.ToBoolean is awful suggestion too... Either suggest full blown stringly typed approach by converting everything to strings and parsing back on every line or for more practical approach use r => r != '0'.
@RufusL - to introduce LINQ and what it can do for you.
@AlexeiLevenkov - that's not really the question here.
I would suggest leaving out the Linq samples, as they are distracting and don't apply to the question. Simply stating that a reference to System.Linq is required should be enough.

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.