Monday, February 4, 2013

Remove foreach with LINQ Aggregate function to append some string

Hello friends,
Take an scenario where you want to append comma(,) with the string in foreach loop

Take an scenario where you want to append comma(,) 
with the string in foreach loop
 
string str=string.Empty;
foreach(ListItem li in cblPercentage.Items)
{
str += li.value + "," ;
}
 
Now you can remove this code with the LINQ Aggregate funtion

string str = cblPercentage.Items.Cast ().Where(item => item.Selected).Aggregate(string.Empty, (current, item) => current + (item.Value + ","));