How to Conditionally Format a String in .Net?

前端 未结 7 773
清酒与你
清酒与你 2020-12-16 09:50

I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows:

Int32 i = 0;
         


        
7条回答
  •  Happy的楠姐
    2020-12-16 10:23

    While not addressing the OP directly, this does fall under the question title as well.

    I frequently need to format strings with some custom unit, but in cases where I don't have data, I don't want to output anything at all. I use this with various nullable types:

    /// 
    /// Like String.Format, but if any parameter is null, the nullOutput string is returned.
    /// 
    public static string StringFormatNull(string format, string nullOutput, params object[] args)
    {
        return args.Any(o => o == null) ? nullOutput : String.Format(format, args);
    }
    

    For example, if I am formatting temperatures like "20°C", but encounter a null value, it will print an alternate string instead of "°C".

    double? temp1 = 20.0;
    double? temp2 = null;
    
    string out1 = StringFormatNull("{0}°C", "N/A", temp1); // "20°C"
    string out2 = StringFormatNull("{0}°C", "N/A", temp2); // "N/A"
    

提交回复
热议问题