How to convert a Foreach loop to Linq (in a datagridview)

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 an 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 accept 1 argument

Many thanks

+3
source share
3 answers

Linq, , "" . Aggregate(), , , . , - List<T>.ForEach(), . # 4.0 , .AsParallel().ForAll(). , , :

List.ForEach():

SuburbGridView.Rows.Cast<GridViewRow>().Where(
    r => ((CheckBox)r.FindControl("SuburbSelector")).Checked).ToList().ForEach(row =>
{
    Response.Write(row.ID);
    // Do something
});

Parallel Linq:

SuburbGridView.Rows.Cast<GridViewRow>().Where(
    r => ((CheckBox)r.FindControl("SuburbSelector")).Checked).AsParallel().ForAll(row =>
{
    Response.Write(row.ID);
    // Do something
});

LINQ. .

, () . FindControl() a System.Web.UI.Control, CheckBox Checked. :

// Doesn't work
(CheckBox)row.FindControl("someCheckbox").Checked

- . .Checked , CheckBox, , CheckBox Control, . parens .

// Works
((CheckBox)row.FindControl("someCheckbox")).Checked

, == true . Checked . , ( ), . - , .

+3

. = :

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

, , , .

+1

I think this should work:

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

What error are you getting?

+1
source

Source: https://habr.com/ru/post/1755680/


All Articles