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