How to convert a DataTable column to a list

I have a DataTable with multiple columns. I want to get a List<String> from the first column of a DataTable. How can i do this?

+48
list c # datatable
Jul 07 2018-11-22T00:
source share
5 answers

Try the following:

 static void Main(string[] args) { var dt = new DataTable { Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } } }; dt.Rows.Add("Lennon", "John"); dt.Rows.Add("McCartney", "Paul"); dt.Rows.Add("Harrison", "George"); dt.Rows.Add("Starr", "Ringo"); List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList(); foreach(string e in s) Console.WriteLine(e); Console.ReadLine(); } 
+67
Jul 08 2018-11-11T00:
source share
 var list = dataTable.Rows.OfType<DataRow>() .Select(dr => dr.Field<string>(columnName)).ToList(); 

[ Edit : add a link to System.Data.DataSetExtensions to the project if this is not compiled]

+34
Jul 07 2018-11-22T00:
source share

Here you go.

  DataTable defaultDataTable = defaultDataSet.Tables[0]; var list = (from x in defaultDataTable.AsEnumerable() where x.Field<string>("column1") == something select x.Field<string>("column2")).ToList(); 

If you need the first column

  var list = (from x in defaultDataTable.AsEnumerable() where x.Field<string>(1) == something select x.Field<string>(1)).ToList(); 
+6
Jul 07 '11 at 22:30
source share

This is what you need?

 DataTable myDataTable = new DataTable(); List<int> myList = new List<int>(); foreach (DataRow row in myDataTable.Rows) { myList.Add((int)row[0]); } 
+5
Jul 07 2018-11-22T00:
source share

I am making a selection for you, and I hope it will be useful ...

  static void Main(string[] args) { var cols = new string[] { "col1", "col2", "col3", "col4", "col5" }; DataTable table = new DataTable(); foreach (var col in cols) table.Columns.Add(col); table.Rows.Add(new object[] { "1", "2", "3", "4", "5" }); table.Rows.Add(new object[] { "1", "2", "3", "4", "5" }); table.Rows.Add(new object[] { "1", "2", "3", "4", "5" }); table.Rows.Add(new object[] { "1", "2", "3", "4", "5" }); table.Rows.Add(new object[] { "1", "2", "3", "4", "5" }); foreach (var col in cols) { var results = from p in table.AsEnumerable() select p[col]; Console.WriteLine("*************************"); foreach (var result in results) { Console.WriteLine(result); } } Console.ReadLine(); } 
+3
Jul 08 2018-11-11T00:
source share



All Articles