views:

86

answers:

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!

A: 

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
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
@Tomas: Thanks! That's what I intended. I've corrected the example. RWFP is excellent... Bravo!
pblasucci
I agree it's less readable, was more curious than anything. Thanks!
Keith
@pblasucci: Thanks!
Tomas Petricek
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("<li>{0}<li>")). (Though this probably isn't something that could ever work nicely in C#)
Tomas Petricek