web-dev-qa-db-fra.com

comment convertir une chaîne en bool

J'ai un string qui peut être "0" ou "1", et il est garanti que ce ne sera pas autre chose.

La question est donc la suivante: quel est le meilleur moyen, le plus simple et le plus élégant de convertir cela en un bool?

Merci.

64
Sachin Kainth

Très simple en effet:

bool b = str == "1";
142
Kendall Frey

Ignorer les besoins spécifiques de cette question, et bien que ce ne soit jamais une bonne idée de convertir une chaîne en un booléen, vous pouvez également utiliser la méthode ToBoolean () sur la classe Convert:

bool val = Convert.ToBoolean("true");

ou une méthode d'extension pour faire tout le mappage bizarre que vous faites:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}
72
Mohammad Sepahvand

Je sais que cela ne répond pas à votre question, mais juste pour aider les autres. Si vous essayez de convertir des chaînes "true" ou "false" en booléens:

Essayez Boolean.Parse

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!
33
live-love
bool b = str.Equals("1")? true : false;

Ou mieux encore, comme suggéré dans un commentaire ci-dessous:

bool b = str.Equals("1");
18
GETah

J'ai créé quelque chose d'un peu plus extensible, reprenant le concept de Mohammad Sepahvand:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }
5
mcfea

J'ai utilisé le code ci-dessous pour convertir une chaîne en booléen. 

Convert.ToBoolean(Convert.ToInt32(myString));
5
yogihosting
    private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };

public static bool ToBoolean(this string input)
{
                return input != null && PositiveList.Any(λ => λ.Equals(input, StringComparison.OrdinalIgnoreCase));
}

Voici ma tentative de conversion de chaîne la plus tolérante qui soit toujours utile, en ne mettant que le premier caractère.

public static class StringHelpers
{
    /// <summary>
    /// Convert string to boolean, in a forgiving way.
    /// </summary>
    /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
    /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
    public static bool ToBoolFuzzy(this string stringVal)
    {
        string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
        bool result = (normalizedString.StartsWith("y") 
            || normalizedString.StartsWith("t")
            || normalizedString.StartsWith("1"));
        return result;
    }
}
2
Mark Meuer

J'aime les méthodes d'extension et c'est celle que j'utilise ...

static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

Ensuite, pour l'utiliser, il suffit de faire quelque chose comme ...

bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True
0
Arvo Bowen

J'utilise ceci:

public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }
0
Hoang Tran