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" });

}

}

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
Solution for #VisualStudio “Internal error in the expression evaluator” by @kunal2383
If you are using Visual Studio 2015, you might have encountered this error “Internal error in the ex...