1

It's easy enough to write, of course, but in C# 2010, is there a built-in Join (or similar) method that will only add a separator if both the previous and next elements are non-null and non-empty?

In other words SmartJoin(", ","Hood","Robin") would produce "Hood, Robin" but SmartJoin(", ", "Robin Hood", string.Empty) would produce simply "Robin Hood".

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • What is the output of `SmartJoin(", ", "First", String.Empty, "Second")`? – jason Jul 13 '11 at 19:42
  • In that case, it should be "First, Second". Sorry, my wording was misleading there...I was thinking only of a two-item list. –  Jul 13 '11 at 19:57

5 Answers5

5

How about this:

public void SmartJoin(string separator, params string[] Items)
{
   String.Join(separator, Items.Where(x=>!String.IsNullOrEmpty(x)).ToArray());
}
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
1

There is no built-in join which you need.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
0

NotherDev was right, strictly speaking, there is no such method build in, but still @CodingGorila solution helped me, and should be added to the next .NET version by my account, though I did still turn it into a static function and have it return a string to make it work in my situation:

public static string SmartJoin(string separator, params string[] Items) {
    return String.Join(separator, Items.Where(x=>!String.IsNullOrEmpty(x)).ToArray());
}
0

NotherDev was right, strictly speaking, there is no such method build in, but still @CodingGorila solution helped me, and should be added to the next .NET version by my account, though I did still turn it into a static function and have it return a string to make it work in my situation:

public static string SmartJoin(string separator, params string[] Items) {
    return String.Join(separator, Items.Where(x=>!String.IsNullOrEmpty(x)));
}
Bart
  • 5,065
  • 1
  • 35
  • 43
0

Here's another way using "aggregate" method of linq

string result = new List<string>() { "Hood", "Robin" }.Aggregate(SmartJoin());
string result2 = new List<string>() { "Robin Hood", "" }.Aggregate(SmartJoin());

private static Func<string, string, string> SmartJoin()
{
  return (x, y) => x + (string.IsNullOrEmpty(y) ? "" : ", " + y);
}
Devin Garner
  • 1,361
  • 9
  • 20