Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neat code to convert bool[] -> "false, true, true, false"

Tags:

arrays

string

c#

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#?

like image 510
AndiDog Avatar asked Feb 16 '10 12:02

AndiDog


4 Answers

var array = new[] { true, false, false };
var result = string.Join(", ", array.Select(b => b.ToString()).ToArray());
Console.WriteLine(result);
like image 69
Darin Dimitrov Avatar answered Sep 19 '22 17:09

Darin Dimitrov


How about:

String.Join(", ", new List<Boolean>() { true, false, false, true }.ConvertAll(x => x.ToString()).ToArray())
like image 37
James Avatar answered Sep 19 '22 17:09

James


arrayOfBools.Select(x => x.ToString()).Aggregate((x, y) => x + ", " + y)
like image 30
Jordão Avatar answered Sep 20 '22 17:09

Jordão


If you are using .NET 4, the following line is enough, because String.Join<T> internally calls the ToString()-method for every item.

Console.WriteLine(string.Join(", ", new[] { false, true, true, false }));

>>>> False, True, True, False
like image 25
ulrichb Avatar answered Sep 18 '22 17:09

ulrichb