要在 .NET 2.0(无 LINQ)中执行此操作,例如用于 SQL-Server ReportingServices 而无需为其编写函数:
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#(适用于从谷歌登陆而不搜索 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);
这假设您的字符串中没有出现退格字符(通常应该是正确的,因为您不能简单地通过键盘输入此字符)。
此外,如果您从数据库中获取值,那么它会更简单,因为您可以直接在 SQL 中执行此操作:
PostgreSQL 和 MySQL:
SELECT
concat_ws(' / '
, NULLIF(searchTerm1, '')
, NULLIF(searchTerm2, '')
, NULLIF(searchTerm3, '')
, NULLIF(searchTerm4, '')
) AS RPT_SearchTerms;
即使使用光荣的 MS-SQL-Server 也是可能的(PS:这是讽刺):
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