Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Foreach loop to Linq (in datagridview)

Tags:

c#

asp.net

linq

foreach (GridViewRow row in gridView.Rows)
{ // Access the CheckBox 
    CheckBox cb = (CheckBox)row.FindControl("SuburbSelector");
    if (cb.Checked)
    {
        //do something;
    }
}

I tried the following and got error

Linq:

var Str = SuburbGridView.Rows.Cast<GridViewRow>().Where(r=>(CheckBox)r.FindControl("SuburbSelector")==checked);

Error:

Delegate 'System.Func < System.Web.UI.WebControls.GridViewRow,int,bool>' does not take 1 arguments

Many thanks

like image 777
Kiddo Avatar asked Nov 28 '25 19:11

Kiddo


1 Answers

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.

like image 112
Samuel Meacham Avatar answered Nov 30 '25 08:11

Samuel Meacham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!