Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 839
Ahmed Atia Avatar asked Jan 16 '10 14:01

Ahmed Atia


2 Answers

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());
}
like image 197
Ahmad Mageed Avatar answered Oct 05 '22 23:10

Ahmad Mageed


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

like image 44
Kris Krause Avatar answered Oct 06 '22 01:10

Kris Krause