关于DataGridViewSelectedCellCollection的LINQ查询

时间:2017-04-13 03:38:20

标签: c# winforms linq datagridview

下面的代码将所选单元格的所有行索引放入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);
    //}

}

1 个答案:

答案 0 :(得分:3)

尝试将SelectedCells投射到IEnumarable<DataGridVewCell>,它应该可以正常工作。

dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct()