views:

53

answers:

2

Best practice when converting DataColumn values to an array of strings?

[Edit] All values for certain DataColumn for all DataTable rows to be converted to an array of string?

A: 

DataRow.ItemArray Property -

http://msdn.microsoft.com/en-us/library/system.data.datarow.itemarray.aspx

Also, which version are you using? You should check out the DataTableExtensions class -

http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.aspx

And the DataRowExtensions class -

http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx

Kris Krause
A: 

If I understood your goal you want to specify a particular column and return all its values as a string array.

Try these approaches out:

int columnIndex = 2; // desired column index

// for loop approach        
string[] results = new string[dt.Rows.Count];
for (int index = 0; index < dt.Rows.Count; index++)
{
    results[index] = dt.Rows[index][columnIndex].ToString();
}

// LINQ
var result = dt.Rows.Cast<DataRow>()
                    .Select(row => row[columnIndex].ToString())
                    .ToArray();

You could replace columnIndex with columnName instead, for example:

string columnName = "OrderId";"

EDIT: you've asked for a string array specifically but in case you're flexible about the requirements I would prefer a List<string> to avoid the need to determine the array length prior to the for loop in the first example and simply add items to it. It's also a good opportunity to use a foreach loop instead.

I would then rewrite the code as follows:

List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
    list.Add(row[columnIndex].ToString());
}
Ahmad Mageed