Using Lambda Expression and LINQ to Concatenate strings in C#

Learnt something cool today on how to use Lambda expression and LINQ to concatenate string in C#.

Using Lambda Expression and LINQ to Concatenate strings in C#

There are couple of ways which I explored using today for concatenating string using LINQ . It includes the usage of the Select function but with the combination ot string.join or LINQ Aggregate function .

Below is a sample sourcecode demonstrating the usage of Lambda Expression and LINQ to Concatenate strings in C#

private void Form1_Load(object sender, EventArgs e)

{

List<BlockbusterMovie> movies = new BlockbusterMovies();

//concatenate string logic

string movieList1 = movies.Select(movie => movie.Name).Aggregate((movie, movie1) => movie + "," + movie1);

//concatenate string logic

string movieList2 = string.Join(",", movies.Select(p => p.Name));

MessageBox.Show(movieList2);

}

public class BlockbusterMovie

{

public string Name { get; set; }

}

public class BlockbusterMovies : List<BlockbusterMovie>

{

public BlockbusterMovies()

{

Add(new BlockbusterMovie { Name = "Vishwaroopam" });

Add(new BlockbusterMovie { Name = "Endhiran" });

Add(new BlockbusterMovie { Name = "Thuppaki" });

Add(new BlockbusterMovie { Name = "Mankatha" });

}

}

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