忽略空字符串的 Join 方法?

NET 方法 String.Join(separator, stringArray)类似于 PHP 的内爆,但是数组中的任何 null 元素都被替换为一个空字符串,所以 that c:

Dim myArray() as String = { "a", null, "c" }
Console.WriteLine(String.Join(", ", myArray));
// Prints "a, , c"

有没有一种简单的方法将一组字符串与忽略空字符串的分隔符连接起来?

我不需要使用数组或者字符串:

("a", "b", "c") --> "a, b, c"
("a", null, "c") --> "a, c"
101733 次浏览

VB.NET

String.Join(",", myArray.Where(Function(s) Not String.IsNullOrEmpty(s)))

C #

String.Join(",", myArray.Where(s => !string.IsNullOrEmpty(s)))

在 CSharp 中可以这样做:

String.Join(",", arr.Where(s => !String.IsNullOrEmpty(s)));

To do it in .NET 2.0 (no LINQ), e.g. for SQL-Server ReportingServices without having to write a function for it:

VB.NET

Dim a As String = "", b As String = "b", c As String = "", d As String = "d", e As String = ""
Dim lala As String = String.Join(" / ", String.Join(vbBack, New String() {a, b, c, d, e}).Split(New Char() {ControlChars.Back}, System.StringSplitOptions.RemoveEmptyEntries))


System.Console.WriteLine(lala)

C # (对于那些从 google 登陆而没有搜索 VB.NET 的用户)

string a = "", b = "b", c = "", d = "d", e = "";
string lala = string.Join(" / ",
string.Join("\u0008",
new string[] { a, b, c, d, e }
).Split(new char[] { '\u0008' }, System.StringSplitOptions.RemoveEmptyEntries)
);


System.Console.WriteLine(lala);

这假设字符退格不出现在字符串中(通常应该为 true,因为不能简单地通过键盘输入该字符)。

另外,如果您从数据库中获取值,那么就更简单了,因为您可以直接在 SQL 中完成:

PostgreSQL & MySQL:

SELECT
concat_ws(' / '
, NULLIF(searchTerm1, '')
, NULLIF(searchTerm2, '')
, NULLIF(searchTerm3, '')
, NULLIF(searchTerm4, '')
) AS RPT_SearchTerms;

And even with the glorious MS-SQL-Server it's possible (PS: that's sarcasm):

DECLARE @in_SearchTerm1 nvarchar(100)
DECLARE @in_SearchTerm2 nvarchar(100)
DECLARE @in_SearchTerm3 nvarchar(100)
DECLARE @in_SearchTerm4 nvarchar(100)


SET @in_SearchTerm1 = N'a'
SET @in_SearchTerm2 = N''
SET @in_SearchTerm3 = N'c'
SET @in_SearchTerm4 = N''


SELECT
COALESCE
(
STUFF
(
(
SELECT ' / ' + RPT_SearchTerm AS [text()]
FROM
(
SELECT NULLIF(@in_SearchTerm1, N'') AS RPT_SearchTerm, 1 AS RPT_Sort
UNION ALL SELECT NULLIF(@in_SearchTerm2, N'') AS RPT_SearchTerm, 2 AS RPT_Sort
UNION ALL SELECT NULLIF(@in_SearchTerm3, N'') AS RPT_SearchTerm, 3 AS RPT_Sort
UNION ALL SELECT NULLIF(@in_SearchTerm4, N'') AS RPT_SearchTerm, 4 AS RPT_Sort
) AS tempT
WHERE RPT_SearchTerm IS NOT NULL
ORDER BY RPT_Sort
FOR XML PATH(N''), TYPE
).value('.', 'nvarchar(MAX)')
,1
,3
,N''
)
,N''
) AS RPT_SearchTerms

试试以下方法:

var finalString = String.Join(",", ExampleArrayOfObjects.Where(x => !String.IsNullOrEmpty(x.TestParameter)).Select(x => x.TestParameter));

这对 VB.NET很有效

Join(*yourArray*.Where(Function(s) Not String.IsNullOrEmpty(s)).ToArray(), *yourDelimiter*)