2013-10-11 52 views
1

我有一个选定单元的集合。由于有多个列,集合中单元格的行索引通常以2,2,2,3,3,3,4,4,4等格式存在。使用细胞集合中的LINQ创建一个int列表

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

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列表中。

回答

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

这应该做你想要什么:

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