将 DataColumn 值转换为字符串数组时的最佳实践? [英] Best practice when converting DataColumn values to an array of strings?

查看:43
本文介绍了将 DataColumn 值转换为字符串数组时的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

将所有 DataTable 行的某些 DataColumn 的所有值转换为字符串数组?

All values for certain DataColumn for 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.

试试这些方法:

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

您可以将 columnIndex 替换为 columnName,例如:

You could replace columnIndex with columnName instead, for example:

string columnName = "OrderId";"

您已经特别要求使用字符串数组,但如果您对要求很灵活,我更喜欢 List 以避免需要在第一个示例中的 for 循环之前确定数组长度,并简单地向其中添加项目.这也是改用 foreach 循环的好机会.

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

这篇关于将 DataColumn 值转换为字符串数组时的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆