136

The VB.NET method String.Join(separator, stringArray) is similar to PHP's implode, but any null elements in the array are replaced with an empty string, so thatc:

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

Is there a simple way to concatenate a set of strings with a separator that ignores empty strings?

I don't necessarily need to use arrays or String.Join or anything else. I just need the following transformations:

("a", "b", "c") --> "a, b, c"
("a", null, "c") --> "a, c"
2
  • As a completely different approach, it might be nice to not add null or empty strings to the array by creating an extension method .AddIfNotEmpty() Commented Feb 18, 2019 at 16:35
  • @JamesWestgate Whether that's a useful approach depends on the mechanism by which the array is populated and whether another part of the program is using the array. Commented Sep 18, 2020 at 13:11

6 Answers 6

232

VB.NET

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

C#

String.Join(",", myArray.Where(s => !string.IsNullOrEmpty(s)))
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting an error: "'Where' is not a member of 'System.Array'". And I don't see anything about 'Where' on MSDN: msdn.microsoft.com/en-us/library/system.array.aspx
I had some luck with this instead: Array.FindAll(myArray, Function(s) Not String.IsNullOrEmpty(s)) Can you either change your answer or explain the Where statement?
Where method is from System.Linq, msdn.microsoft.com/en-us/library/bb534803.aspx
68

You can do it like this in CSharp:

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

2 Comments

What's the purpose of posting exactly the same thing as the accepted answer stackoverflow.com/a/16326071/461444 two years later ?
@AFract: Check this stackoverflow.com/posts/16326071/revisions the post you mentioned was edited early this year and at that time they updated the original answer added sample for C#
7

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# (for those landing from google and not searching for 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);

This assumes that the character backspace doesn't occur in your strings (should usually be true, because you can't simply enter this character by keyboard).

Also, if you get the values from a database, then it's even simpler, since you can do it in SQL directly:

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 

3 Comments

SQL Server now has concat_ws() as of SQL Server 2017 (14.x)
OP never even mentioned any dabase in his question. This very well may be an anwser, but not to the question posted.
@Doug: i posted in 2016, sql server 2017 wasn't out back then. So yes, now you can use the concat_ws just like in pl/pgsql.
5

Another option would be to use LINQ's handy null filter:

String.Join(",", myArray.OfType<string>())

Comments

0

Try the following:

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

1 Comment

kindly consider adding more information in your answer
-2

This works fine for VB.NET

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.