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

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

问题描述

最佳实践?


对于某些的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";"

编辑:你问一个字符串数组明确,但如果你是灵活的关于我preFER一个列表与LT的要求;串&GT; 来避免需要确定数组长度之前的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.

我会再改写code如下:

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天全站免登陆