derekantrican derekantrican - 6 months ago 33
C# Question

"Smart" way to concatenate strings?

I'm looking for a "smart" way to concatenate strings with a separator. Obviously I could code all this out myself so I'm wondering if there is a simple way (LINQ or maybe some other method that I don't know) to do this.

Say I have a set of strings (this can be any number of strings):

string s1 = "a";
string s2 = "b";
string s3 = "c";

And I want to concatenate the strings such that the result is something like
a, b, c
. This is easy enough, but here's the twist: if any of the strings are empty, I don't want the extra comma.

For instance, if this is my set:

string s1 = "";
string s2 = "b";
string s3 = "c";

I want the result to be
b, c
(or just
if both
are empty).

Is there a simple way to do this?

Answer Source

caveat - not tested - there may be typos or misremebered syntax.

var list = new List<String>{"a","b","", null);
var res = string.join(",", list.where(s=>!string.isnullorempty(s)));

and capitalization too!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download