将DataColumn值转换为字符串数组时的最佳做法?

将DataColumn值转换为字符串数组时的最佳做法?

[编辑]某些DataColumn的所有值,以便将所有DataTable行转换为字符串数组?

如果我理解了你的目标,你想要指定一个特定的列并将其所有值作为字符串数组返回。

尝试这些方法:

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() .Select(row => row[columnIndex].ToString()) .ToArray(); 

您可以使用columnName替换columnIndex ,例如:

 string columnName = "OrderId";" 

编辑:你已经特别要求一个字符串数组,但是如果你对这些要求很灵活,我宁愿使用List来避免在第一个例子中在for循环之前确定数组长度,只需添加它的项目。 这也是使用foreach循环的好机会。

然后我会重写代码如下:

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

我知道这个问题已经过时了,但我发现它在我的Google搜索中尝试做类似的事情。 我想从我的数据表的特定行中包含的所有值创建一个列表。 在下面的代码示例中,我使用GUI向导在Visual Studio中向我的项目添加了一个SQL数据源,并将所需的表适配器放入设计器中。

 '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)