Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a boolean array into a string using c#

Tags:

c#

I have an array that looks something like:

status[0] = true
status[1] = true
status[2] = false
status[3] = true

In reality it's larger but still less than 20. I need to convert this into "ABD". Where each true represents an ordered letter in the alphabet. Can anyone think of an easy really efficient way to do this?

like image 550
Beth Avatar asked Feb 27 '26 03:02

Beth


2 Answers

My napkin says this might work...

StringBuilder sb = new StringBuilder();
for(int i = 0; i < status.Length; i++)
{
   if(status[i])
   {
       sb.Append((char)('A' + i));
   }
}

string result = sb.ToString();
like image 80
Jon Avatar answered Mar 02 '26 16:03

Jon


string input = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

string result = new String(input.ToCharArray()
                      .Take(status.Length)
                      .Where((c, i) => status[i]).ToArray());
like image 44
Bala R Avatar answered Mar 02 '26 16:03

Bala R



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!