2012-10-05 54 views
0

有沒有辦法從DataTable中的單個列中提取所有項目而不是使用For Each循環?從DataTable提取列

例如,下面的建立KeyValuePair從每行一個列表中的一個DataTable

List<KeyValuePair<string, double>> extract = new List<KeyValuePair<string, double>>(); 
foreach (DataRow item in _dataTableTest.Rows) 
{ 
    KeyValuePair<string, double> selection = (KeyValuePair<string, double>)item["Selection"]; 
    extract.Add(selection); 
} 

一列有沒有更好的方式和/或更快的方式做到這一點?

回答

4

你可以使用Linq-To-DataTable

List<KeyValuePair<string, double>> extract = _dataTableTest.AsEnumerable() 
      .Select(r => r.Field<KeyValuePair<string, double>>("Selection")) 
      .ToList(); 

請注意,您需要添加using System.Linq;並認爲這是不是在性能方面的「快」。它也在內部使用循環。