C # - DataGridView and SelectedCells - Searching row indices of selected cells

What is the cleanest way to ask a DataGridView to return "row indexes that cells selected"? This is not the same as DataGridView.SelectedRows. I do not allow row or column selection. Therefore, users must select cell blocks. I just need to find out which rows the cells selected in them.

Is there any clever lambda expression that I should use? What would you do?

If this helps: In the code I'm writing, I already inherited from DataGridView, and I am in my own class DataGridViewExt.

+5
source share
2 answers

LINQ Solution:

var rowIndexes = dgv.SelectedCells.Cast<DataGridViewCell>()
                                  .Select(cell => cell.RowIndex)
                                  .Distinct();

Edit:

. , DataGridViewSelectedCellCollection IEnumerable<DataGridViewCell>, IEnumerable, , , Object. :

int[] rowIndexes = (from sc in this.SelectedCells.Cast<DataGridViewCell>() 
                    select sc.RowIndex).Distinct().ToArray();
+9
IEnumerable<int> indexes = 
 (from c in dataGridView1.SelectedCells.Cast<DataGridViewCell>()
  select c.RowIndex).Distinct();
+1

All Articles