How to use a Linq aggregate with single quotes

Suppose I have a rowset, for example:

IList<string> myList = new List<string>(){"one", "two", "three"};

Using myList.Aggregate, I would like to add "one", "two", "three" (including single quotes)

Does anyone have an easy way to do this just using the aggregation function? I thought something in the lines

myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));

but only half the solution.

+1
source share
2 answers

Any reason to use Aggregate, not simpler string.Join?

string joined = string.Join(", ", myCollection.Select(x => "'" + x + "'"));

(add a call ToArrayif you are using .NET 3.5.)

string.Join Aggregate ( StringBuilder), . , , :

string csv = myCollection.Aggregate(new StringBuilder("'"),
                 (sb, x) => sb.AppendFormat("{0}', '"),
                 sb => { sb.Length -= 3;
                         return sb.ToString(); });
+6

" " "), :

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 , .

EDIT: , ,.

+2

Source: https://habr.com/ru/post/1676283/


All Articles