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

can I write something like this with lambdas?

Igal Tabachnik
  • 31,174
  • 15
  • 92
  • 157
  • And for the simpler array cases there is String.Join( ",", stringArray ) see: http://msdn.microsoft.com/en-us/library/tk0xe5h0.aspx – Kris May 10 '09 at 12:03

5 Answers5

18

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

Example:

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

EDIT

Although the original title (and example) was about concatenating strings with a separator (to which String.Join() does the best job in my opinion), the original poster seems to ask about the broader solution: how to apply a custom format a list of strings.

My answer to that is write your own method. String.Join has a purpose, reflected by its name (joins some strings). It's high chance that your format logic has a meaning in your project, so write it, give it a proper name and use it.

For instance, if you want to output <li>text</li> for every item, make something as 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 concatenating strings in a loop.

Dan C.
  • 3,643
  • 2
  • 21
  • 19
  • Much tidier than wrestling with Lambdas in my opinion – codeulike May 10 '09 at 10:18
  • 1
    The original question is: can I write something like this with lambdas? This isn't closest answer. I also would use String.Join in simple strings concatenation. But adding some complex logic makes this function useless. – Kamarey May 10 '09 at 10:36
  • @Kamarey: While the OP was talking of loops and lambdas, this is the correct answer to the problem of converting an array of strings into a string string with separators. – Richard May 10 '09 at 11:05
  • @Kamarey: the original question was first "convert a string[] to string with out using foreach". If he's going to use lambdas for that... well, it's his code, in his project :). And if you're adding some extra logic, I still wouldn't use lambdas for that; make it a separate method then. – Dan C. May 10 '09 at 12:02
  • well, its still good to have this answer here for other people who are pondering similar questions – codeulike May 10 '09 at 12:28
  • i like your solution. but it wouldn't work if i wanted to enclose each element with something like
  • string
  • i should have made it more clear in my post –  May 10 '09 at 22:25
  • @decon: If you wanted that, you'd better make it a separate method and use a StringBuilder to format the results in a loop. I still wouldn't use a lambda for that. – Dan C. May 11 '09 at 06:31