Is it possible to construct a stringbuilder using a lambda function instead of foreach? [duplicate]
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.ToStr开发者_开发问答ing();
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!
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.
精彩评论