125

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"
Doug
  • 2,400
  • 2
  • 18
  • 24
  • 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() – James Westgate Feb 18 '19 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. – Stewart Sep 18 '20 at 13:11

6 Answers6

218

VB.NET

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

C#

String.Join(",", myArray.Where(s => !string.IsNullOrEmpty(s)))
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Damith
  • 62,401
  • 13
  • 102
  • 153
  • I'm getting an error: "'Where' is not a member of 'System.Array'". And I don't see anything about 'Where' on MSDN: http://msdn.microsoft.com/en-us/library/system.array.aspx – Doug May 02 '13 at 12:55
  • 2
    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? – Doug May 02 '13 at 13:44
  • 8
    `Where` method is from `System.Linq`, http://msdn.microsoft.com/en-us/library/bb534803.aspx – Damith May 02 '13 at 13:47
66

You can do it like this in CSharp:

String.Join(",", arr.Where(s => !String.IsNullOrEmpty(s)));
KyleMit
  • 30,350
  • 66
  • 462
  • 664
SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • 1
    What's the purpose of posting exactly the same thing as the accepted answer https://stackoverflow.com/a/16326071/461444 two years later ? – AFract Aug 29 '17 at 07:21
  • 17
    @AFract: Check this https://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# – SharpCoder Aug 29 '17 at 14:01
5

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 
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
3

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

String.Join(",", myArray.OfType<string>())
Ryan Naccarato
  • 674
  • 8
  • 12
0

Try the following:

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

This works fine for VB.NET

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

Aida
  • 2,174
  • 2
  • 16
  • 33