C# 将IEnumerable转换为List
我想要一个包含此DataGridView中所有“选定”系列代码的列表: 我可以将它们作为DataGridViewRow获取,例如:C# 将IEnumerable转换为List,c#,winforms,linq,linq-to-objects,C#,Winforms,Linq,Linq To Objects,我想要一个包含此DataGridView中所有“选定”系列代码的列表: 我可以将它们作为DataGridViewRow获取,例如: List<DataGridViewRow> selectedSeriesCodes = gridSeriesList.Rows.Cast<DataGridViewRow>().Where(g => !string.IsNullOrEmpty(g.Cells[List
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();
但我的目标是将它们作为一个列表,纯粹用于分离关注点,因为我不想将控件传递到业务逻辑中以简化测试,仅供参考这是一个excel vsto插件
我原以为将LINQ与anon类型一起使用就可以了,但它不会编译,例如:
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”到
“System.Collections.Generic.List”。显式转换
你缺演员吗
我确信这是可能的,否则我将只使用for循环。您丢失了。ToList:
你失踪了。托利斯:
您不需要选择新的匿名类型。只需选择value.ToString;为了消除将结果转换为列表的需要,让业务代码需要一个IEnumerable。您不需要选择新的匿名类型。只需选择value.ToString;为了消除将结果转换为列表的需要,让业务代码需要IEnumerable.+1,而不是返回DataGridViewTextBoxCell,我根据@NickBedford的提示输入.Value以获取字符串。谢谢大家。+1,我没有返回DataGridViewTextBoxCell,而是根据@NickBedford的提示输入了.Value来获取字符串。谢谢各位。
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();