How to Conditionally Format a String in .Net?

前端 未结 7 768
清酒与你
清酒与你 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条回答
  • 2020-12-16 10:20

    I hoped this could do it:

    return String.Format(items.ToString(itemList + " ;;") + "Values: {0}", valueList);
    

    Unfortunately, it seems that the .ToString() method doesn't like the blank negative and zero options or not having a # or 0 anywhere. I'll leave it up here in case it points someone else to a better answer.

    0 讨论(0)
  • 2020-12-16 10:22

    Well, you can simplify it a bit with the conditional operator:

    string formatString = items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}";
    return string.Format(formatString, itemList, valueList);
    

    Or even include it in the same statement:

    return string.Format(items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}",
                         itemList, valueList);
    

    Is that what you're after? I don't think you can have a single format string which sometimes includes bits and sometimes it doesn't.

    0 讨论(0)
  • 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:

    /// <summary>
    /// Like String.Format, but if any parameter is null, the nullOutput string is returned.
    /// </summary>
    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"
    
    0 讨论(0)
  • 2020-12-16 10:26

    This is probably not what you're looking for, but how about...

    formatString = (items.Count > 0) ? "Items: {0}; Values: {1}" : "Values: {1}";
    
    0 讨论(0)
  • 2020-12-16 10:28

    Not within String.Format(), but you could use C#'s inline operators, such as:

    return items.Count > 0 
           ? String.Format("Items: {0}; Values: {1}", itemList, valueList)
           : String.Format("Values: {0}", valueList);           
    

    This would help tidy-up the code.

    0 讨论(0)
  • 2020-12-16 10:35
    string.Format(  (items.Count > 0 ? "Items: {0}; " : "") + "Values {1}"
                  , itemList
                  , valueList); 
    
    0 讨论(0)
提交回复
热议问题