I have a DataTable that contains a single row. I want to convert this DataTable values into a string array such that i can access the column values of that DataTable through the string array index For example, if my DataTable is as follows
| Name | Address | Age |
-------------------------------
| jim | USA | 23 |
I want to store the values in that Datatable into my string array such that MyStringArray[1] will give me the value USA.
Thanks in Advance
Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row
:
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
You could then access one:
MyStringArrays.ElementAt(0)[1]
If you use linqpad, here is a very simple scenario of your example:
class Datatable
{
public List<data> rows { get; set; }
public Datatable(){
rows = new List<data>();
}
}
class data
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
void Main()
{
var datatable = new Datatable();
var r = new data();
r.Name = "Jim";
r.Address = "USA";
r.Age = 23;
datatable.rows.Add(r);
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
var s = MyStringArrays.ElementAt(0)[1];
Console.Write(s);//"USA"
}
Very easy:
var stringArr = dataTable.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
Where DataRow.ItemArray
property is an array of objects containing the values of the row for each columns of the data table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With