c# - DataGridViewSelectedCellCollection 上的 LINQ 查询

标签 c# winforms linq datagridview

下面的代码将选定单元格的所有行索引放入一个列表框中。它运作良好但看起来很麻烦。

我想知道为什么注释循环不起作用。

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);
    //}

}

最佳答案

尝试将 SelectedCells 转换为 IEnumarable<DataGridVewCell>它应该有效。

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

关于c# - DataGridViewSelectedCellCollection 上的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43383137/

相关文章:

c# - System.ObjectDisposeException。处理流编写器的正确方法是什么?

c# - 以安全的方式发送电子邮件

c# - 使用字符串字段名称动态构建具有层次结构的 linq 查询?

c# - Linq Take 通过集合做额外的传递

c# - 我应该尽可能使用 const string 而不是 string 吗?

C# WPF 加密

winforms - 显示和隐藏面板(Powershell GUI)

c# - 如何将 CheckedListBox 项目设置为默认选中

c# - 在哈希集字典中查找值的组合

c# - 使用委托(delegate)在表单之间进行通信