Convert string [] to string using outeach

string x;
foreach(var item in collection)
{
   x += item+",";
}

      

Can I write something like this with lambdas?

0


a source to share


5 answers


string[] text = new string[] { "asd", "123", "zxc", "456" };

var result = texts.Aggregate((total, str) => total + "," + str);

      



Shorter syntax, thanks to Earwicker

+1


a source


Assuming C #, have you tried String.Join ()? Or are you using mandatory lambdas?

Example:

string[] myStrings = ....;
string result = String.Join(",", myStrings);

      

EDIT

While the original title (and example) was about concatenating delimited strings (which String.Join()

does the best job in my opinion), the original poster seems to be asking for a broader solution: how to apply a custom format to a list of strings.



My answer to this question is - write your own method. String.Join has a purpose as reflected by its name (concatenates some strings). This is a high chance that your formatting logic makes sense in your project, so write it, give it the correct name, and use it.

For example, if you want to output <li>text</li>

for each element, do this:

string FormatAsListItems(string[] myStrings)
{
    StringBuilder sb = new StringBuilder();
    foreach (string myString in myStrings)
    {
         sb.Append("<li>").Append(myString).Append("</li>");
    }
}

      

I think the intent is clearer and you also don't take the performance hit of string concatenation in a loop.

+18


a source


string x = string.Join(",", collection);

      

+5


a source


You are looking too far for a solution. The class String

has a method Join

for this:

string x = String.Join(",", collection);

      

+2


a source


Does this answer your question?

Most efficient way to concatenate strings?

Note that you can do it with Aggregate

, but the built-in is string.Join

easier to use and faster for long arrays.

+1


a source







All Articles