Q:

C# condition within ForEach to say at least one item has been processed

Time and time again I find myself needing to loop through a list/collection to process each item individually as well as checking to see if at least one item has been processed. For example, if I have a 'Create User' method to see which 'User Roles' need to be added to a user (by way of ticking some check boxes), I would have something that looks like:
                foreach (CheckBox in CheckBoxRepeater)

                {
                    if (CheckBox.Checked)
                    {
                        userRoles.Add(SomeUserRole);
                        foundOne = true;
                    }
                }

                if (foundOne)
                {
                    //Do something else
                }

My question is: can the foreach and if statements above be combined somehow? or is it best practice to have a bool (in the example above = 'foundOne') to track that an item has been processed?
Thanks!

A:

You can try using Linq, providing that userRoles is a List<T>:
 // Data to work with - filtered items
 var data = CheckBoxRepeater
   .Where(checkBox => checkBox.Checked);

 // Add all the items into a List<T> - userRoles 
 userRoles.AddRange(data);

 // Do we have any items filtered?
 if (data.Any()) 
 {
    ...
 }

