C# DataGridViewSelectedCellCollection上的LINQ查询
下面的代码将选定单元格的所有行索引放入列表框中。它工作得很好,但看起来很笨重 我想知道为什么被评论的循环不起作用C# DataGridViewSelectedCellCollection上的LINQ查询,c#,winforms,linq,datagridview,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
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);
//}
}
private void dataGridView1\u选择已更改(对象发送方,事件参数e)
{
listBox1.Items.Clear();
DataGridView dgv=(DataGridView)发送方;
列表索引=新列表(){};
foreach(dgv中的DataGridViewCell单元格。SelectedCells)
{
index.Add(cell.RowIndex);
}
foreach(index.Distinct()中的int rowindex)
{
listBox1.Items.Add(行索引);
}
//下面的循环尝试执行相同的操作,但不起作用。
//foreach(dgv.SelectedCells.AsQueryable()中的int-rowindex.Select(x=>x.rowindex.Distinct())
//{
//listBox1.Items.Add(行索引);
//}
}
尝试将所选单元格强制转换为一个IEnumarable
,它应该可以工作
dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct()
dgv.SelectedCells.Cast().Select(x=>x.RowIndex).Distinct()
尝试将所选单元格强制转换为一个IEnumarable
,它应该可以工作
dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct()
dgv.SelectedCells.Cast().Select(x=>x.RowIndex).Distinct()
而不知道什么不起作用。尝试将SelectedCells强制转换为IEnumerabledgv.SelectedCells.Cast().Select(x=>x.RowIndex).Distinct()
谢谢@energ1ser,您解决了它!我以前从来没有用过“Cast”,不知道什么不起作用。尝试将SelectedCells强制转换为IEnumerabledgv.SelectedCells.Cast().Select(x=>x.RowIndex).Distinct()
谢谢@energ1ser,您解决了它!我以前从来没有用过“Cast”。