LINQ with CheckBox List–LINQ Tips

Dear All,

There are many situation where you need to comma separated values of all the checked items of a checkbox list for this situation you generally write following  code

string allowedProductfamilies = string.Empty;
foreach (ListItem lItem in chkFamily.Items)
                {
                    if (lItem.Selected)
                    {
                        allowedProductfamilies += lItem.Value + ",";
                    }
                }

Now the above code is fine but can be improve more with following lines of code you can directly replace above lines with following lines of the code

string allowedProductfamilies = string.Empty;

allowedProductfamilies = chkFamily.Items.Cast<ListItem>().Where(lItem => lItem.Selected).Aggregate(allowedProductfamilies, (current, lItem) => current + (lItem.Value + ","));

 

I am sure you like the code.

Enjoy .Net , Enjoy LINQ .

Your Friend,

Rajat Jaiswal