2017-04-13 17 views
0

下面的代码将所选单元格的所有行索引放入ListBox中。它运作良好,但看起来很麻烦。对DataGridViewSelectedCellCollection的LINQ查询

我不知道为什么评论循环不会工作。

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

不知道什么不工作。尝试将SelectedCells投射到IEnumerable 'dgv.SelectedCells.Cast ()。Select(x => x.RowIndex).Distinct()' – energ1ser

+0

Thanks @ energ1ser,你解决了它!我从来没有使用过“演员”。 – uqji

回答

1

尝试将SelectedCells投射到IEnumarable<DataGridVewCell>,它应该有效。

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