净C#的string.join如何输出"零"而不是空字符串,如果元素值为null?

编程入门 行业动态 更新时间:2024-10-27 11:29:18
本文介绍了净C#的string.join如何输出"零"而不是空字符串,如果元素值为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据href="msdn.microsoft/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?

本文发布于:2023-11-04 12:33:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:值为   而不是   元素   空字符串   join

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!