简体   繁体   中英

Extract column from DataTable

Is there a way to extract all items from a single column in a DataTable instead of using a For Each loop?

Eg, the following builds a List of KeyValuePair from each Row in a single column of a 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);
}

Is there a better way and/or quicker way to do this?

You could use Linq-To-DataTable

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

Note that you need to add using System.Linq; and that this is not "quicker" in terms of performance. It also uses loops internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM