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

Share:

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...