开发者

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 fo开发者_JS百科r all DataTable rows to be converted to an array of string?


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());
}


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


I know this question is old, but I found it in my Google search trying to do something similar. I wanted to create a list from all the values contained in a specific row of my datatable. In my code example below, I added a SQL datasource to my project in Visual Studio using the GUI wizards and I dropped the needed table adapter into the designer.

'Create a private DataTable
Private authTable As New qmgmtDataSet.AuthoritiesDataTable

'Fill the private table using the table adapter 
Me.AuthoritiesTableAdapter1.Fill(Me.authTable)

'Make the list of values
Dim authNames As List(Of String) = New List(Of String)(From value As qmgmtDataSet.AuthoritiesRow In Me.authTable.Rows Select names.authName)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜