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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...