问题描述
让我们假设我有一系列字符串,例如:
IList<string> myList = new List<string>(){"one", "two", "three"};
使用myList.Aggregate我想以"一个','',两个','三'""(包括单语引号)
有人只使用聚合函数来做到这一点吗?我在想
的线myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));
,但这只是解决方案的一半.
推荐答案
有什么理由使用Aggregate而不是简单的string.Join?
string joined = string.Join(", ", myCollection.Select(x => "'" + x + "'"));
(如果您使用的.NET 3.5.)
you can 使用Aggregate(理想情况下使用StringBuilder),但这并不令人愉快.假设有一个非空的收藏,i think 这应该做到这一点:
string csv = myCollection.Aggregate(new StringBuilder("'"), (sb, x) => sb.AppendFormat("{0}', '"), sb => { sb.Length -= 3; return sb.ToString(); });
其他推荐答案
由于您指定"仅使用聚合函数",如何:
myCollection.Aggregate(string.Empty, (soFar, next) => soFar + (soFar == string.Empty ? soFar : ", ") + "'" + next + "'")
(或)
myCollection.Aggregate(string.Empty, (soFar, next) => string.Format("{0}{1}'{2}'", soFar, soFar == string.Empty ? soFar : ", ", next))
以这种方式使用Aggregate来进行字符串串联确实效率低下.
编辑:更新以摆脱领先的,.
问题描述
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.
推荐答案
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(); });
其他推荐答案
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 ,.