3

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.

2 Answers 2

12

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.

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

4 Comments

The test should be chr == '1' as you are comparing characters.
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!
@Darin: Feel free to just edit the post next time, when it's clearly a typo. ;)
@Peter: No prob, glad it does the job.
2

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())); }));

1 Comment

weekdaysEnabled1 is wrong : 'allWeekdays' is right It'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

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.