如果对象为null,则返回空字符串

时间:2012-12-13 19:53:51

标签: c# linq

对象i来自数据库。 PrDT是一个字符串,PrDateTime是DataTimeOffset类型,可以为空

vi.PrDT = i.PrDateTime.Value.ToString("s");

快捷方式是什么? 我不想要别的等等......

5 个答案:

答案 0 :(得分:9)

使用conditional operator

vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
                                  string.Empty;

答案 1 :(得分:5)

您可以执行扩展方法:

public static class NullableToStringExtensions
{
    public static string ToString<T>(this T? value, string format, string coalesce = null)
        where T : struct, IFormattable
    {
        if (value == null)
        {
            return coalesce;
        }
        else
        {
            return value.Value.ToString(format, null);
        }
    }
}

然后:

vi.PrDT = i.PrDateTime.ToString("s", string.Empty);

答案 2 :(得分:2)

string.Format("{0:s}", i.PrDateTime) 

如果空字符串为空,则上面将返回一个空字符串。由于Nullable<T>.ToString检查空值并返回空字符串(如果是),否则返回字符串表示(但不能使用格式说明符)。 Trick是使用string.Format,它允许你使用你想要的格式说明符(在这种情况下,s)并仍然得到Nullable<T>.ToString行为。

答案 3 :(得分:1)

return (i.PrDateTime.Value ?? string.Empty).ToString();

刚刚测试过,它似乎有效。

答案 4 :(得分:-1)

return i.PrDateTime.Value.ToString("s") ?? string.Empty;