C# 如何在 .Net 中有条件地格式化字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/154483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Conditionally Format a String in .Net?
提问by Adam Tegen
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;
i.ToString("$#,##0.00;($#,##0.00);Zero");
The above code would result in one of three formats if the variable is positive, negative, or zero.
如果变量是正数、负数或零,上面的代码将导致三种格式之一。
I would like to know if there is any way to use sections on string arguments. For a concrete, but contrivedexample, I would be looking to replace the "if" check in the following code:
我想知道是否有任何方法可以在字符串参数上使用部分。对于一个具体但人为设计的示例,我希望替换以下代码中的“if”检查:
string MyFormatString(List<String> items, List<String> values)
{
string itemList = String.Join(", " items.ToArray());
string valueList = String.Join(", " values.ToArray());
string formatString;
if (items.Count > 0)
//this could easily be:
//if (!String.IsNullOrEmpty(itemList))
{
formatString = "Items: {0}; Values: {1}";
}
else
{
formatString = "Values: {1}";
}
return String.Format(formatString, itemList, valueList);
}
回答by Kon
This is probably not what you're looking for, but how about...
这可能不是你要找的东西,但怎么样...
formatString = (items.Count > 0) ? "Items: {0}; Values: {1}" : "Values: {1}";
回答by Chris Wenham
Not within String.Format(), but you could use C#'s inline operators, such as:
不在 String.Format() 中,但您可以使用 C# 的内联运算符,例如:
return items.Count > 0
? String.Format("Items: {0}; Values: {1}", itemList, valueList)
: String.Format("Values: {0}", valueList);
This would help tidy-up the code.
这将有助于整理代码。
回答by Jon Skeet
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.
那是你追求的吗?我不认为你可以有一个单一的格式字符串,有时包含位,有时不包含。
回答by Joel Coehoorn
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.
不幸的是,似乎 .ToString() 方法不喜欢空白的负数和零选项,也不喜欢任何地方都没有 # 或 0。我会把它留在这里,以防它为其他人指出更好的答案。
回答by Mark Cidade
string.Format( (items.Count > 0 ? "Items: {0}; " : "") + "Values {1}"
, itemList
, valueList);
回答by Andrey Agibalov
Just don't. I have no idea what are both the items and values in your code, but I believe, this pair could be treated as an entity of some kind. Define this entity as a class and override its ToString()
method to return whatever you want. There's absolutely nothing wrong with having if
for deciding how to format this string depending on some context.
只是不要。我不知道你的代码中的项目和值是什么,但我相信,这对可以被视为某种实体。将此实体定义为一个类并覆盖其ToString()
方法以返回您想要的任何内容。if
根据某些上下文来决定如何格式化这个字符串绝对没有错。
回答by JYelton
While not addressing the OP directly, this does fall under the question title as well.
虽然不直接解决 OP,但这也属于问题标题。
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".
例如,如果我将温度格式化为“20°C”,但遇到空值,它将打印替代字符串而不是“°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"