Home > Net >  Linq: List all Rows in DataGridView that contain at least 2 cells with a Value
Linq: List all Rows in DataGridView that contain at least 2 cells with a Value

Time:09-30

I want to filter all rows in a DataGridView that contain at least two Cells with a specific value, but starting at third column.

What I have:

var filteredRows = new List<DataGridViewRow>();
foreach (DataGridViewRow row in myDataGridView.Rows) {
    if (row.Cells.Cast<DataGridViewCell>().Where(x => x.ColumnIndex > 1 && x.Value != null && (int)x.Value == 10).Count() >= 2) {
        filteredRows.Add(row);
    }
}

I'd like to have the whole thing in Linq syntax.

Thank you for your ideas!

CodePudding user response:

You can use LINQ's SelectMany:

myDataGridView.Rows.SelectMany(row => row.Cells.Cast<DataGridViewCell>().Where(x => x.ColumnIndex > 1 && x.Value != null && (int)x.Value == 10).Count() >= 2))

CodePudding user response:

You can use a where instead of a if

myDataGridView.Rows
  .where(row => row.Cells.Cast<DataGridViewCell>()
               .Count(x => 
                            x.ColumnIndex > 1 &&
                            x.Value != null &&
                            (int)x.Value ==10) >= 2
        ).ToList();
  • Related