MadBoy
MadBoy

Reputation: 11104

Merging strings together with separator berween them in C#

I needed to merge strings that are inside List<string> together into oneliner. I came up with simple solution but I am not sure if it's the best way to go.

First version with problematic , on string start:

string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
    benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}

Second version (Linq power) but still with ` :

string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s);

Working version without , but amount of lines makes some pain in later reading it:

   int b = 0;
   string benchmarkiUjemneDatyRazem = "";
   foreach (string s in benchmarkiUjemne) {
       if (b == 0) {
          b = 1;
          benchmarkiUjemneDatyRazem = s;
          continue;
       }
       benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
  }

Final version that I came up with was based on Linq with Subsitute to first char:

    string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s).Substring(1);

Is this good approach to this problem ? Or there's better way to actually do it? Like using StringBuilder or so?

Upvotes: 0

Views: 90

Answers (2)

Sven
Sven

Reputation: 22683

If you're using .Net 4, you can use string.Join (in earlier versions this will work only if benchmarkiUjemne is a string[]):

string result = string.Join(",", benchmarkiUjemne);

If this is .Net 3.5 or older, you can still use it by calling ToArray on the list:

string result = string.Join(",", benchmarkiUjemne.ToArray());

Upvotes: 6

Oded
Oded

Reputation: 499002

Use string.Join:

var res = string.Join(",", benchmarkiUjemne);

Upvotes: 3

Related Questions