Skip to main content
 首页 » 编程设计

c#之使用 LINQ 从单元格集合创建一个 int 列表

2024年02月01日28yjmyzz

我有一组选定的单元格。由于有多个列,集合中单元格的行索引通常采用 2,2,2,3,3,3,4,4,4 等格式。

我想获取这些单元格的行索引列表。

List<int> selectedRows = new List<int>(); 
 
List<DataGridViewCell> cellCollection = dGV_model.SelectedCells.Cast<DataGridViewCell>() 
                                      .GroupBy(cell => cell.RowIndex) 
                                      .Select(cell => cell.First()) 
                                      .ToList<DataGridViewCell>(); 
foreach (DataGridViewCell cell in cellCollection) 
{ 
    selectedRows.Add(cell.RowIndex); 
} 

基本上,我的问题是如何从单个 LINQ 查询创建一个 int 列表?现在,我必须遍历 cellcollection 以将它们添加到一个 int 列表中。

请您参考如下方法:

var selectedRows = dGV_model.SelectedCells.Cast<DataGridViewCell>() 
                                          .Select(c=>c.RowIndex).Distinct() 
                                          .ToList();