下面的代码将所选单元格的所有行索引放入ListBox中。它运作良好,但看起来很麻烦。
我想知道为什么评论的循环不起作用。
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
DataGridView dgv = (DataGridView)sender;
List<int> indices = new List<int>() { };
foreach (DataGridViewCell cell in dgv.SelectedCells)
{
indices.Add(cell.RowIndex);
}
foreach (int rowindex in indices.Distinct())
{
listBox1.Items.Add(rowindex);
}
//The following loop attempts to do the same, but wont work.
//foreach (int rowindex in dgv.SelectedCells.AsQueryable().Select(x => x.RowIndex).Distinct())
//{
// listBox1.Items.Add(rowindex);
//}
}
答案 0 :(得分:3)
尝试将SelectedCells投射到IEnumarable<DataGridVewCell>
,它应该可以正常工作。
dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct()