5
votes

What is the cleanest way to ask a DataGridView to return "indexes of rows that have selected cells"? This is not the same as DataGridView.SelectedRows. I don't allow Row or Column selection. So users must select blocks of cells. I just need to find out which rows have selected cells in them.

Is there some clever lambda expression I should be using? What would you do?

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

2
I feel like there should be some kind of SELECT DISTINCT in LINQ syntax that I should be doing.BuddyJoe
Should be doing or could be doing?Jay Riggs
Should be - in the sense that someone else will support this codebase a year from now... And if I can describe the intent in 1 line rather than 3 to 5 that would be better for this project.BuddyJoe

2 Answers

10
votes

LINQ solution:

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

Edit:

You were just missing the Cast. It's needed because DataGridViewSelectedCellCollection doesn't implement a generic IEnumerable<DataGridViewCell>, just IEnumerable, so when you enumerate the values, they are of type Object. With the cast, that would give:

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