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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s