将DataColumn的值转换为字符串数组时的最佳实践是什么?

16

将DataColumn的值转换为字符串数组时的最佳实践是什么?

[编辑] 将某个DataTable中特定DataColumn的所有值转换为字符串数组?


2
你能具体说明吗?任何Datarow都有ItemArray属性,它会按照定义的列顺序返回一个对象数组。将对象转换为字符串只需在每个值上调用ToString()方法即可,但也许你想要其他的东西... - flq
DataColumn的值需要转换为字符串数组,但我正在寻找最佳实现方法。 - Ahmed Atia
3个回答

30

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

尝试以下方法:

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

你可以用columnName代替columnIndex,例如:

string columnName = "OrderId";"

编辑: 你要求使用字符串数组,但如果对要求灵活的话,我更喜欢使用List<string>。这样可以避免在第一个示例中在for循环之前确定数组长度并简单地添加项的需要。同时也是使用foreach循环的好机会。

然后我会按以下方式重写代码:

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

2

1
DataRow.ItemArray 返回一行中的所有值作为数组。我认为 OP 想要将一列中的所有值作为数组返回。也许您可以扩展您的答案,以帮助解释 DataRow.ItemArrayDataTableExtensions 类如何提供帮助? - Ben

1
我知道这个问题已经很老了,但是在我进行谷歌搜索时发现了它,试图做类似的事情。我想从我的数据表中特定行包含的所有值创建一个列表。在下面的代码示例中,我使用GUI向我的项目添加了一个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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接