问题
Let's assume that I have a collection of strings, like so:
IList<string> myList = new List<string>(){"one", "two", "three"};
Using myList.Aggregate I would like to end up with "'one', 'two', 'three'" (including single quotes)
Does someone have a sleak way of doing this, only using the Aggregate function? I was thinking something in the lines of
myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));
but that's only half the solution.
回答1:
Any reason to use Aggregate rather than the simpler string.Join?
string joined = string.Join(", ", myCollection.Select(x => "'" + x + "'"));
(Add a ToArray call if you're using .NET 3.5.)
You can implement string.Join using Aggregate (ideally using a StringBuilder) but it's not terribly pleasant. Assuming a non-empty collection, I think this should do it:
string csv = myCollection.Aggregate(new StringBuilder("'"),
(sb, x) => sb.AppendFormat("{0}', '"),
sb => { sb.Length -= 3;
return sb.ToString(); });
回答2:
Since you specify "only using the Aggregate function", how about:
myCollection.Aggregate(string.Empty, (soFar, next) =>
soFar + (soFar == string.Empty ? soFar : ", ")
+ "'" + next + "'")
(or)
myCollection.Aggregate(string.Empty, (soFar, next) =>
string.Format("{0}{1}'{2}'",
soFar, soFar == string.Empty ? soFar : ", ", next))
Using Aggregate in this manner for string concatenation is really inefficient though.
EDIT: Updated to get rid of the leading ,.
来源:https://stackoverflow.com/questions/8095480/how-to-use-linq-aggregate-with-single-quotes