1

Possible Duplicate:
LINQ to append to a StringBuilder from a String[]

Forgive my functional programming noobiness, but is it even possible to use a lamba function to append each string in an array to a StringBuilder object?

Is it possible to turn this code:


// string[] errors = ...
StringBuilder sb = new StringBuilder("<ul>");

foreach (var error in errors)
{
    sb.AppendFormat("<li>{0}</li>", error);
}

sb.AppendLine("</ul");
return sb.ToString();


Into something like this:


// string[] errors = ...
StringBuilder sb = new StringBuilder("<ul>");

//I know this isn't right, I don't care about a return value
errors.All(s => sb.AppendFormat("<li>{0}</li>", s));

sb.AppendLine("</ul");
return sb.ToString();


Thanks for any edification!

Community
  • 1
  • 1
Keith
  • 2,618
  • 4
  • 29
  • 44

1 Answers1

1

I haven't tested it, but something like the following should work...

return errors.Aggregate(new StringBuilder("<ul>"), (sb,s) => sb.AppendFormat("<li>{0}</li>", s))
             .Append("</ul>");
             .ToString();

Aggregate is an IEnumerable extension method... But I might have the order of agruments wrong. Personally, I do not think this buys you much since it less readable, and is doing a foreach internally anyway.

pblasucci
  • 1,738
  • 12
  • 16
  • I think this should work, except the lambda function parameters should be "(sb, s) => .." (the first parameter is current state, which is the string builder, the second one is a signle error string from the 'errors' collection. – Tomas Petricek Feb 02 '10 at 19:29
  • @Tomas: Thanks! That's what I intended. I've corrected the example. RWFP is excellent... Bravo! – pblasucci Feb 02 '10 at 20:19
  • I agree it's less readable, was more curious than anything. Thanks! – Keith Feb 02 '10 at 20:26
  • Regarding readability - I think this is a case where partial function application could make the code a bit nicer. Imagine you could write just: Aggregate(..., StringBuilder.AppendFormat("
  • {0}
  • ")). (Though this probably isn't something that could ever work nicely in C#)
  • – Tomas Petricek Feb 02 '10 at 21:43