How to Concatenate strings inside a List using Lambda Expression in C# ?

If you have a Generic list of type string in C# and you wish to concatenate the items of the list to a single string along with the delimiter character , one of the easiest way to do it is using LINQ or Lambda Expression.

How to Concatenate strings inside a List using Lambda Expression in C# ?

Below is a C# code that shows how to achieve the functionality using Lambda expression  . The aggregate method that is available in the System.Linq namespace is used to concatenate the strings inside the collection.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace DeveloperPublishApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> inputList = new List<string>() { "DeveloperPublish", "programming", "website", "on Windows Phone" };
            var result = ConcatenateList(inputList,",");
	     Console.WriteLine(result);
            Console.ReadLine();
        }
        // Function to concatenate 
        public static string ConcatenateList(List<string> input,string delimiter)
        {
            var result = input.Aggregate((i, j) => i + delimiter + j);
            return result;
        }
    }
    
}

image

No Responses

Leave a Reply