2012-03-13 147 views
0

我想包含來自該DataGridView中所有的 '選擇' 系列代碼的List<string>轉換一個的IEnumerable <AnonymousType#1>列出<string>

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>爲關注點分離,我不想控制傳遞到業務邏輯,以減輕測試,只是一個供參考,這是一個excel VSTO插件-在。

我想使用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

你並不需要選擇一個新的匿名類型。只需'選擇value.ToString();'並刪除需要將結果轉換爲列表具體而言,請將業務代碼需要IEnumerable 。 – 2012-03-13 03:40:25

回答

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(); 
+0

+ 1,而不是DataGridViewTextBoxCell被返回,我把.Value獲取字符串的@NickBedford的提示。多謝你們。 – 2012-03-13 03:49:17

相關問題