Modify All Elements in a Collection With A Single Line of Code Image

Modify All Elements in a Collection With A Single Line of Code

January 6, 2015      .net Programming

I recently had a project with a couple of CheckBoxLists and I wanted to pre-check all items in each list. I could have used a traditional foreach loop but for the sake of something new and different, sought out a way to use Linq and do it in a single line. Here is what I came up with:

MyList.Items.Cast<ListItem>().ToList().ForEach(i => i.Selected = true); 

Is is better than a foreach loop? I haven't done empirical testing, but for code readability it wins!

The nice thing is that this technique can be applied to any Linq query...

Share It