净C#的string.join如何输出"零"而不是空字符串,如果元素值为null? [英] .Net C# String.Join how to output "null" instead of empty string if element value is null?

查看:541
本文介绍了净C#的string.join如何输出"零"而不是空字符串,如果元素值为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx" rel="nofollow"> MSDN文档进行的string.join 如果任何

在code我翻出数据从一个DataTable的

  rotationValues​​ =的string.join<对象>(,
    从在rotationData.Rows.OfType&所述ř; DataRow的>()选择 -  [R [5]);
 

这将导致输出与此类似:

  8,7,12,13,
 

有没有办法简单地有它把空的地方,像这样一个空字符串:

  8,7,空,12,NULL,NULL,13,空
 

解决方案

您可以选择

 研究[5]? 空值
 

而不是仅仅研究[5]

此外,只需删除<对象>当你调用泛型方法部分。它仍然是一个的IEnumerable<对象> 您加入,但是编译器会自动推断类型参数

意见后增加:

研究[5] 可能的 的DBNull.Value 。那么,这是不是一个真正的空引用,但其的ToString 实现返回。因此,在这种情况下,的string.join 文件是不严格有关。因此,尽量选择像

 (R [5] == NULL || DBNull.Value.Equals(R [5]))? 空,R [5]
 

或者

 (R [5] == NULL ||  -  [R [5]是为DBNull)? 空,R [5]
 

希望它帮助。

According to the MSDN docs for String.Join "If any element in value is null, an empty string is used instead."

The code I have pulls data out of a DataTable

rotationValues = string.Join<object>(", ",
    from r in rotationData.Rows.OfType<DataRow>() select r[5]);

This would result in output similar to this:

8, 7, , 12, , , 13, 

Is there any way to simply have it put "null" in place of an empty string like so:

8, 7, null, 12, null, null, 13, null

解决方案

You can select

r[5] ?? "null"

instead of just r[5].

Also, just remove the <object> part when you call the generic method. It will still be an IEnumerable<object> that you join, but the compiler will infer the type parameter automatically.

ADDITION after comment:

Your r[5] might be DBNull.Value. Then, this is not a "real" null reference, but its ToString implementation returns "". So in that case, the string.Join documentation wasn't strictly relevant. Therefore, try to select something like

(r[5] == null || DBNull.Value.Equals(r[5])) ? "null" : r[5]

or maybe

(r[5] == null || r[5] is DBNull) ? "null" : r[5]

Hope it helps.

这篇关于净C#的string.join如何输出&QUOT;零&QUOT;而不是空字符串,如果元素值为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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