2012-03-16 8 views
38

stringは "0"か "1"のいずれかであり、それは他のものではないことが保証されています。文字列をboolに変換する方法

質問:これをboolに変換するには、どのような方法が最も簡単で、最も簡単で最も洗練された方法ですか?

ありがとうございました。

+0

任意の予期しない値が入力にすることができた場合は、TryParse(http://stackoverflow.com/questions/18329001/parse-to-boolean-or-check-string-value/を使用することを考えます18329085#18329085) –

答えて

113

実にシンプル:

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

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

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

私は 'x? true:false'ユーモラスな。 –

+4

'bool b = str.Equals(" 1 ")'一見すると、うまく動作し、直感的に動作します。 –

37

この質問の特定のニーズを無視し、その決して良いながら、文字列をブールにキャストするアイデアは、ConvertクラスのToBoolean()メソッドを使用することです。

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

またはあなたがやっている奇妙なものは何でもマッピングを行うための拡張メソッド:

public static class MyStringExtensions 
{ 
    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 a weird value to a bool!"); 
     } 
    } 
} 
+0

Convert.ToBooleanの動作(http://stackoverflow.com/questions/7031964/what-is-the-difference-between-convert-tobooleanstring-and-boolean-parsestrin/26202581#26202581 –

5

を私はムハンマド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)); 
    } 
13

Iこれがあなたの質問に答えるのではなく、ただ他の人を助けることを知っています。あなたはブール値を「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! 
+0

Powershellスクリプト用に必要)いくつかのXMLデータを読んで、これは完璧です! – Alternatex

2

を試してみてくださいここでは基本的にキーイング、なお有用であるブール値への変換最も寛容な文字列での私の試みです最初の文字だけをオフにします。

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

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

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

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

+0

Mohammad Sepahvandを見て、Michael Freidgeimのコメントにお答えください! – TamusJRoyce

0
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)); 
} 
関連する問題