How to Conditionally Format a String in .Net?

前端 未结 7 792
清酒与你
清酒与你 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: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.

提交回复
热议问题