Linq doesn't seem to have a good "each" aggregate. There is Aggregate()
, which I don't like if I'm not actually accumulating anything, since the accumulator value is essentially thrown away. I don't think there's anything equivalent to List<T>.ForEach()
, and it's a shame. If you're using C# 4.0, and don't mind processing in parallel, you could use .AsParallel().ForAll()
. So anyway, here's a few ways to do what you want:
Using List.ForEach()
:
SuburbGridView.Rows.Cast<GridViewRow>().Where(
r => ((CheckBox)r.FindControl("SuburbSelector")).Checked).ToList().ForEach(row =>
{
Response.Write(row.ID);
// Do something
});
And using Parallel Linq:
SuburbGridView.Rows.Cast<GridViewRow>().Where(
r => ((CheckBox)r.FindControl("SuburbSelector")).Checked).AsParallel().ForAll(row =>
{
Response.Write(row.ID);
// Do something
});
I'm just getting the hang of this LINQ stuff myself. I love it.
By the way, you were just missing an extra pair of ()
's around your cast. FindControl()
returns a System.Web.UI.Control
, and you have to cast it to CheckBox
to access the Checked
property. You can't do it like this:
// Doesn't work
(CheckBox)row.FindControl("someCheckbox").Checked
That doesn't work because of the order of operations. The .Checked
is evaluated before the cast to CheckBox
, which means you're trying to access a CheckBox
property of Control
, and it doesn't exist. The extra pair of parens fixes that.
// Works
((CheckBox)row.FindControl("someCheckbox")).Checked
And one last thing, you don't need to do == true
in your comparison. Checked
is already a boolean value. If you like it there for clarity (some people do), then by all means keep it. It's not considered bad practice or anything, it's just a matter of preference.