views:

60

answers:

2

Hi,

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.

+5  A: 

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.

Noldorin
The test should be `chr == '1'` as you are comparing characters.
Darin Dimitrov
Thats what I love about stackoverflow, you ask a question and a minute later you have ur answer ;D you have to change the double quotes in to single quotes though cuz we're dealing with chars but otherwise this compiles ok :D Thanks!
Peter
@Darin: Feel free to just edit the post next time, when it's clearly a typo. ;)
Noldorin
@Peter: No prob, glad it does the job.
Noldorin
+1  A: 

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())); }));
Florian
thank god for LINQ right ;-) thanks for the helpfull addon.
Peter
weekdaysEnabled1 is wrong : 'allWeekdays' is rightIt's just a more concise syntax, but I think the number of conversion is the same :( I don't know why the public static bool ToBoolean(char value) method is not implemented in the framework
Florian