How to use Linq aggregate with single quotes

我是研究僧i 提交于 2019-12-14 02:26:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!