C# – LINQ Select certain cell in DataGridView depending on other cell in row

cdatagridviewlinq

I am brand spanking new to LINQ and am trying to use it in my current hobby project. I have a datagridview where the first cell of each row is a datagridviewcheckbox, and the 4th cell is a string.

If the checkbox is checked, I need to add the 4th cell's value to a list.

At first I tried:

var selectedID = from c in multiContactLookup.SelectedCells.Cast<DataGridViewCell>() 
                              select multiContactLookup.Rows[c.RowIndex].Cells[4].Value;

That didn't work because the checked cells are programatically unselected so c is never a value.

Then I tried:

var sel2 = from r in multiContactLookup.Rows.Cast<DataGridViewRow>()
                       where r.Cells[0].Value is true select r.Cells[4].Value;

but somehow my syntax is wrong.

Using LINQ, how can I select the rows where the first cell is checked then select the value of the first cell? Do I have to split this into two collections?

Thank you!

Best Answer

I think this should work:

IEnumerable<string> values = multiContactLookup.Rows.Cast<DataGridViewRow>()
    .Where(row => (bool)row.Cells[0].Value)
    .Select(row => (string)row.Cells[3].Value);
Related Topic