开发者

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()开发者_StackOverflow中文版)),
    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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜