将IEnumerable <anonymoustype#1>转换为List <string> </string> </anonymoustype#1>

时间:2012-03-13 03:31:54

标签: c# winforms linq linq-to-objects

我希望List<string>包含此DataGridView中的所有“已选定”系列代码:

enter image description here

我可以将它们作为DataGridViewRow获取,例如:

List<DataGridViewRow> selectedSeriesCodes =
                gridSeriesList.Rows.Cast<DataGridViewRow>().Where(g =>
                    !string.IsNullOrEmpty(g.Cells[ListDataSource.gridColumn1].Value.ToString()) &&
                    Convert.ToBoolean(g.Cells[ListDataSource.gridColumn1].Value) == true).ToList();

但是我的目标是将它们作为一个List<string>纯粹用于分离关注点,因为我不想将控件传递给业务逻辑以简化测试,而只是一个fyi这是一个excel vsto插件。< / p>

我认为使用带有anon类型的LINQ可以解决问题,但它不会编译,例如:

List<string> selectedSeriesCodes = from x in gridSeriesList.Rows.Cast<DataGridViewRow>()
                                       where (!string.IsNullOrEmpty(x.Cells[ListDataSource.gridColumn1].Value.ToString()) &&
                                        Convert.ToBoolean(x.Cells[ListDataSource.gridColumn1].Value) == true)
                                       select new { SeriesCode = x.Cells[ListDataSource.gridColumn2].ToString() };
  

错误'System.Collections.Generic.IEnumerable <AnonymousType#1>'到   'System.Collections.Generic.List <string>'。显式转换   存在(你是否错过演员表?)

我确信这是可能的,否则我只会使用for循环。

1 个答案:

答案 0 :(得分:4)

您遗失.ToList()

List<string> selectedSeriesCodes = 
(from x in gridSeriesList.Rows.Cast<DataGridViewRow>()
where !string.IsNullOrEmpty(x.Cells[ListDataSource.gridColumn1].Value.ToString() 
      &&  Convert.ToBoolean(x.Cells[ListDataSource.gridColumn1].Value) == true)
select x.Cells[ListDataSource.gridColumn2].ToString()).ToList();