开发者

Is it possible to construct a stringbuilder using a lambda function instead of foreach? [duplicate]

开发者 https://www.devze.com 2022-12-19 12:11 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: LINQ to append to a StringBuilder from a String[]
This question already has answers here: Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消