Can .NET convert “Yes” & “No” to boolean without If?

后端 未结 12 634
情话喂你
情话喂你 2020-12-17 14:15

You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:

CType(\"Yes\", Boolean)

相关标签:
12条回答
  • 2020-12-17 14:45
    private static bool GetBool(string condition)
    {
        return condition.ToLower() == "yes";
    }
    
    GetBool("Yes"); // true
    GetBool("No"); // false
    

    Or another approach using extension methods

    public static bool ToBoolean(this string str)
    {
        return str.ToLower() == "yes";
    }
    
    bool answer = "Yes".ToBoolean(); // true
    bool answer = "AnythingOtherThanYes".ToBoolean(); // false
    
    0 讨论(0)
  • 2020-12-17 14:48

    C# 6+ version:

    public static bool StringToBool(string value) => 
        value.Equals("yes",           StringComparison.CurrentCultureIgnoreCase) ||
        value.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase) || 
        value.Equals("1");`
    
    0 讨论(0)
  • 2020-12-17 14:51

    If you think about it, "yes" cannot be converted to bool because it is a language and context specific string.

    "Yes" is not synonymous with true (especially when your wife says it...!). For things like that you need to convert it yourself; "yes" means "true", "mmmm yeeessss" means "half true, half false, maybe", etc.

    0 讨论(0)
  • 2020-12-17 14:57

    Using this way, you can define conversions from any string you like, to the boolean value you need. 1 is true, 0 is false, obviously.
    Benefits: Easily modified. You can add new aliases or remove them very easily.
    Cons: Will probably take longer than a simple if. (But if you have multiple alises, it will get hairy)

    enum BooleanAliases {
          Yes = 1,
          Aye = 1,
          Cool = 1,
          Naw = 0,
          No = 0
     }
     static bool FromString(string str) {
          return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str));
     }
     // FromString("Yes") = true
     // FromString("No") = false
     // FromString("Cool") = true
    
    0 讨论(0)
  • 2020-12-17 14:58

    Slightly off topic, but I needed once for one of my classes to display 'Yes/No' instead of 'True/False' in a property grid, so I've implemented YesNoBooleanConverter derived from BooleanConverter and decorating my property with <TypeConverter(GetType(YesNoBooleanConverter))> _...

    0 讨论(0)
  • 2020-12-17 14:59

    I like the answer that @thelost posted, but I'm reading values from an ADO.Net DataTable and the casing of the string in the DataTable can vary.

    The value I need to get as a boolean is in a DataTable named childAccounts in a column named Trades.

    I implemented a solution like this:

    bool tradeFlag = childAccounts["Trade"].ToString().Equals("yes", StringComparison.InvariantCultureIgnoreCase);
    
    0 讨论(0)
提交回复
热议问题