Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Join method that ignores empty strings?

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" 
like image 898
Doug Avatar asked May 01 '13 20:05

Doug


People also ask

What is string join method?

The string join() method returns a string by joining all the elements of an iterable (list, string, tuple), separated by the given separator.

Does join Return string?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How does empty string work?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


2 Answers

VB.NET

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

C#

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

like image 151
Damith Avatar answered Oct 21 '22 13:10

Damith


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

like image 40
SharpCoder Avatar answered Oct 21 '22 15:10

SharpCoder