如果不为null,则设置字符串格式

本文关键字:设置 字符串 格式 null 如果不 | 更新日期: 2023-09-27 18:21:35

在这种情况下,我需要通过CSV(制表符分隔)输出一个信息数据集。

问题是,如果列值包含一个值,那么它需要被双引号引用。

值类型的范围可以从字母数字字符串到DateTime格式的值。

我想知道是否有比这更简单的方法:

(string.IsNullOrWhiteSpace(evt.Name)?null:string.Format("'"{0}'"", evt.Name))

对于要导出为字符串值的每个值。

编辑2013-07-08 11:06 CST(修改为11:17 CST)

public string QuoteFormat(object val)
{
    if(val != null) {
        if(val == typeof(string))
            val = (val as string).Replace("'"" , "'"'"");
        return string.Format("'"{0}'"" , val);
    }
    return null;
}

如果不为null,则设置字符串格式

您询问是否有一种方法可以更清楚地表达您的问题。虽然您自己的代码很好,而且我们认为它没有问题,但我建议您使用扩展。

public static class GoldBishopExtensions
{
    public static string Transform(this string source, Func<string, string> transform, string fallback = null)
    {
        return !String.IsNullOrWhiteSpace(source) 
                   ? transform(source) 
                   : fallback;
    }
}

然后与一起使用

// Return "evt.Name" if String is not null or whitespaces
// return null otherwise
evt.Name.Transform(name => String.Format("'"{0}'"", name));

或者:

// Return ("evt.Name") if String is not null or whitespaces
// return (No Value) otherwise
evt.Name.Transform(name => String.Format("'"{0}'"", name), "No Value");

但正如评论中所说,你并不真的需要这个,因为你的代码很好。

编辑:对于您自己的特定问题,您的扩展可以是:

public static class GoldBishopExtensions
{
    public static string Quote(this string source, string fallback = null)
    {
        return !String.IsNullOrWhiteSpace(source) 
                   ? String.Format("'"{0}'"", source) 
                   : fallback;
    }
}
evt.Name.Quote();

我对您发布的函数做了一个小调整,如果valnull,只返回""。此显式声明如果valnull,则不需要字符。

public string QuoteFormat(object val)
{
    if(val != null) {
        // This is fine if there is an additional requirement to double existing quotes
        if(val == typeof(string))
            val = (val as string).Replace("'"" , "'"'"");
        // if you are using dates and the default format is fine, then this will work.
        // otherwise I would suggest formatting the date before passing in and perhaps
        // changing the parameter to string
        return string.Format("'"{0}'"" , val);
    } else {
        return "";
    }
}

如果你想返回null,你可以放置一个null字符串,让你知道结果是null:

string result = String.Format("'"{0}'"", evt.Name ??"null");//output -> "null"
//string result = String.Format("'"{0}'"", evt.Name ??null);// output -> ""