views:

392

answers:

7

How would you convert an array of booleans to a string like "false, true, true, false" - using as few lines of code as possible?

Python allows me to use the following (very nice and clean):

", ".join(map(str, [False, True, True, False]))

In C#, string.Join only allows me to join an array of strings.

So what is a short way to do the same in C#?

+1  A: 
var boolStrings = string.Join(",", new List<bool> { false, true, true, false }
      .ConvertAll(x => x.ToString()).ToArray());
mythz
+3  A: 

How about:

String.Join(", ", new List<Boolean>() { true, false, false, true }.ConvertAll(x => x.ToString()).ToArray())
James
This would throw a `InvalidCastException`.
João Angelo
@Joao, yeah just compiled it there, updated using ConvertAll
James
You can remove the `()` after `new List<Boolean>` when you specify elements.
Alex Bagnolini
That's fine if he already has a list, but the question specified an array. To use ConvertAll in that case, you'd first have to construct the list from the array, then do the conversion. LINQ `Select` works in both cases.
tvanfosson
@tvanfosson...to be fair it is easy enough to convert an array to a list e.g. new List<Boolean>(MyArrayOfBool). However, I do agree the Select on this occassion would be the way to go.
James
@James - note, though, that it requires 50% more storage (3 times the original amount at the peak) to create the list, then do the conversion and end up with the converted elements than it does to use `Select`.
tvanfosson
+21  A: 
var array = new[] { true, false, false };
var result = string.Join(", ", array.Select(b => b.ToString()).ToArray());
Console.WriteLine(result);
Darin Dimitrov
A: 

Something along the lines of

var s = from item in blnArray select item.Tostring();

Then use the enumerable s to populate the string array?

Not actually tested this - this is just how I might approach it if I were asked to look at it...

Martin Milan
Thanks for the edit John - I've now learned (indent) how to mark text as code...
Martin Milan
A: 
 var str = string.Join(", ", new List<Boolean>() {false, true, false}.ToArray());
 Console.WriteLine(str.ToString());
Islam Ibrahim
A: 
var bools = new bool[] {false, true, true, false};
var strings = bools.Aggregate((x,y) => x.ToString()+","+y.ToString());
Joel Coehoorn
Doesn't seem to work because the lambda return value must be boolean.
AndiDog
+1  A: 
arrayOfBools.Select(x => x.ToString()).Aggregate((x, y) => x + ", " + y)
Jordão