Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char Array/string to bool Array

We have this field in our database indicating a true/false flag for each day of the week that looks like this : '1111110'

I need to convert this value to an array of booleans.

For that I have written the following code :

char[] freqs = weekdayFrequency.ToCharArray();
bool[] weekdaysEnabled = new bool[]{
    Convert.ToBoolean(int.Parse(freqs[0].ToString())), 
    Convert.ToBoolean(int.Parse(freqs[1].ToString())),
    Convert.ToBoolean(int.Parse(freqs[2].ToString())),
    Convert.ToBoolean(int.Parse(freqs[3].ToString())),
    Convert.ToBoolean(int.Parse(freqs[4].ToString())),
    Convert.ToBoolean(int.Parse(freqs[5].ToString())),
    Convert.ToBoolean(int.Parse(freqs[6].ToString()))
};

And I find this way too clunky because of the many conversions.

What would be the ideal/cleanest way to convert this fixed length string into an Array of bool ??

I know you could write this in a for-loop but the amount of days in a week will never change and therefore I think this is the more performant way to go.

like image 534
Peter Avatar asked May 18 '26 21:05

Peter


2 Answers

A bit of LINQ can make this a pretty trivial task:

var weekdaysEnabled = weekdayFrequency.Select(chr => chr == '1').ToArray();

Note that string already implements IEnumerable<char>, so you can use the LINQ methods on it directly.

like image 97
Noldorin Avatar answered May 21 '26 10:05

Noldorin


In .NET 2

bool[] weekdaysEnabled1 =
Array.ConvertAll<char, bool>(
    freqs,
    new Converter<char, bool>(delegate(char c) { return Convert.ToBoolean(int.Parse(freqs[0].ToString())); }));
like image 37
Florian Avatar answered May 21 '26 12:05

Florian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!