文字列をブール値に変換する方法


90

私はstring「0」または「1」のいずれかであることができるを持っています、そしてそれが他のものにならないことが保証されています。

したがって、問題は、これをに変換するための最良の、最も単純で、最もエレガントな方法はbool何ですか?


3
入力に予期しない値が含まれる可能性がある場合は、TryParse(stackoverflow.com/questions/18329001/…)の使用を検討してください
Michael Freidgeim 2017年

回答:



79

この質問の特定のニーズを無視し、文字列をブール値にキャストすることは決して良い考えではありませんが、1つの方法はConvertクラスでToBoolean()メソッドを使用することです

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

または、実行している奇妙なマッピングを実行するための拡張メソッド:

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!");
        }
    }
}


1
フィールBoolean.TryParseは、値の多くは、それがスローされませんように変換する必要がある場合に好適であるFormatExceptionようConvert.ToBoolean
user3613932 2018年

47

私はこれがあなたの質問に答えないことを知っていますが、他の人々を助けるためだけです。「true」または「false」の文字列をブール値に変換しようとしている場合:

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!

いくつかのXMLデータを読み取るPowershellスクリプトに必要であり、これは完璧です!
オルタ

20
bool b = str.Equals("1")? true : false;

または、以下のコメントで示唆されているように、さらに良いです:

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

39
私はどんな形でもx ? true : falseユーモラスだと思います。
ケンダルフレイ

5
bool b = str.Equals("1") 一見すると問題なく直感的に動作します。
Erik Philips

@ErikPhilips文字列strがNullで、NullをFalseとして解決したい場合は、それほど直感的ではありません。
MikeTeeVee

7

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

以下のコードを使用して、文字列をブール値に変換しました。

Convert.ToBoolean(Convert.ToInt32(myString));

「1」と「0」の2つの可能性しかない場合は、Convert.ToInt32を呼び出す必要はありません。他のケースを検討したい場合は、var isTrue = Convert.ToBoolean( "true")== true && Convert.ToBoolean( "1"); //両方とも正しい。
TamusJRoyce 2017

MohammadSepahvandの回答MichaelFreidgeimのコメントを見てください!
TamusJRoyce 2017

3

これは、基本的に最初の文字のみをキーオフする、依然として有用な最も寛容な文字列からブール値への変換の試みです。

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;
    }
}

3
    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));
}

1

私はこれを使用します:

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

私は拡張メソッドが大好きで、これは私が使用するものです...

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;
    }
}

次に、それを使用するには、次のようなことを行います...

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

-1

文字列がスローされた例外なしで有効なブール値であるかどうかをテストしたい場合は、これを試すことができます:

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

出力is Boolean およびstringToBool2の出力は次のとおりです: 'ブール値ではありません'

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.