Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save datatable first column in array C#

Tags:

c#

datatable

I have this kind of datatable:

Name | CategorieID | FullCategorie_ID ----  -------------  ----------------  A        1             12    B        1             13  C        5             14  D        3             15  E        6             16 

I want to save the values of column Name in an array, I am using this to get the values of a row. E.g. To get the values of the first row I can use the following code.

var stringArr =datatable1.Rows[0].ItemArray.Select(x => x.ToString()).ToArray(); 

But I don't know how to get all the values of the only first column.

like image 799
Kamran Avatar asked Dec 17 '13 08:12

Kamran


People also ask

How do you store data table values in an array?

Replace type with the data type of your single column (e.g. int , string , ...) and myField with the name of your single column. var myArray = (from row in myDataTable. AsEnumerable() select row. Field<type>("myField")).

How to convert DataTable to Array in c#?

Very easy: var stringArr = dataTable. Rows[0]. ItemArray.

How to convert DataTable column to string Array in c#?

Select(row => row["columnName"]. ToString()). ToArray();


2 Answers

I suggest to use LINQ to DataSet for querying DataTable:

datatable1.AsEnumerable().Select(r => r.Field<string>("Name")).ToArray(); 
like image 100
Sergey Berezovskiy Avatar answered Oct 02 '22 12:10

Sergey Berezovskiy


Mode classic

List<String> stringArr = new List<String>();  // Classic version :-) for( int a = 0 ; a < datatable1.Rows.Count ; a ++) {     stringArr.Add(datatable1.Rows[a]["Name"].ToString()); } 
like image 26
Mehdi Bugnard Avatar answered Oct 02 '22 12:10

Mehdi Bugnard