C# - DataGridView和SelectedCells - 查找所选单元格的行索引

Bud*_*Joe 5 .net c# datagridview winforms

请求DataGridView返回"已选择单元格的行的索引"的最简洁方法是什么?这与DataGridView.SelectedRows不同.我不允许选择行或列.因此用户必须选择单元格块.我只需要找出哪些行中选择了单元格.

我应该使用一些聪明的lambda表达式吗?你会怎么做?

如果这有帮助:在我写的代码中,我已经从DataGridView继承而且我在我自己的自定义类DataGridViewExt中.

Met*_*ght 9

LINQ解决方案:

var rowIndexes = dgv.SelectedCells.Cast<DataGridViewCell>()
                                  .Select(cell => cell.RowIndex)
                                  .Distinct();
Run Code Online (Sandbox Code Playgroud)

编辑:

你刚刚错过了Cast.这是必需的,因为DataGridViewSelectedCellCollection不实现泛型IEnumerable<DataGridViewCell>,只是IEnumerable,因此当您枚举值时,它们是类型Object.使用演员表,这会给:

int[] rowIndexes = (from sc in this.SelectedCells.Cast<DataGridViewCell>() 
                    select sc.RowIndex).Distinct().ToArray();
Run Code Online (Sandbox Code Playgroud)