如何有条件地设置格式在.net中的字符串? [英] How to Conditionally Format a String in .Net?

查看:128
本文介绍了如何有条件地设置格式在.net中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做的字符串一些条件格式。我知道,你可以做的整数部分条件格式和彩车如下:

 的Int32 I = 0;
i.ToString($#,## 0.00;($#,## 0.00);零);
 

以上code会导致三种格式之一,如果变量是正数,负数或零。

我想知道是否有任何方式使用部分的字符串参数。对于一个具体的,但做作的例子,我将寻求以取代如果检查以下code:

 字符串MyFormatString(名单<字符串>项目名单,其中,字符串>数值)
{
    串ITEMLIST =的string.join(,items.ToArray());
    串valueList =的string.join(,values​​.ToArray());

    字符串的formatString;

    如果(items.Count大于0)
    //这可以很容易地:
    //如果(!String.IsNullOrEmpty(ITEMLIST))
    {
        formatString的=的相关文件:{0},值:{1};
    }
    其他
    {
        formatString的=值:{1};
    }

    返回的String.Format(formatString中,ITEMLIST,valueList);
}
 

解决方案

那么,你可以把它简化一点与条件运算符:

 字符串的formatString = items.Count> 0? 的相关文件:{0},值:{1}:值:{1};
返回的String.Format(formatString中,ITEMLIST,valueList);
 

甚至包括它在同一个语句:

 返回的String.Format(items.Count大于0?的相关文件:{0},值:{1}:值:{1},
                     ITEMLIST,valueList);
 

这就是你追求的是什么?我不认为你可以有一个格式字符串有时包括位,有时没有。

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 contrived example, I would be looking to replace the "if" check in the following code:

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);
}

解决方案

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.

这篇关于如何有条件地设置格式在.net中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆