Home » C# » Linq Aggregate to concatenate string with a comma

Linq Aggregate to concatenate string with a comma

If you have an array that you want to flatten into a string with a comma between each entry, you could use Linq with a one liner delegate to reach this goal.

string flatten = inputs.Aggregate((current, next) => 
                                 string.Format("{0}, {1}", current, next))

This is quite powerful as you can see, you do not have to do validation to know if you have reach the last entry to not add a trailing comma. Without Linq and the aggregate function, you would have to loop and to verify this condition.

string flatten = string.Empty;
for(int i = 0 ; i < inputs.Length ; i++)
{
   if(i!=(i.Length-1))
   {
       flatten += str + ", ";
   }
   else
   {
       flatten += str;
   }
}

I don’t know for you, but I found more easy to read the Aggregate method than the second snippet of code.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 Responses so far.

  1. This is a good example of the Aggregate function, but you do realise you could always just use String.Join.

    If it’s a trivial operation that sounds like a lot of other people would also have done it, do a quick Google first.

    • Of course, this is more a very simple example of how to use Aggregate with Linq. You could use Aggregate with a more difficult task and use String.Join for this simple task. Good remark Derek.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.