C# 将数据行值转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9620434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:13:16  来源:igfitidea点击:

Getting datarow values into a string?

c#ado.netdatarow

提问by Kevin

I have a dataset called "results" with several rows of data. I'd like to get this data into a string, but I can't quite figure out how to do it. I'm using the below code:

我有一个名为“结果”的数据集,其中包含几行数据。我想把这些数据变成一个字符串,但我不太清楚如何去做。我正在使用以下代码:

string output = "";
foreach (DataRow rows in results.Tables[0].Rows)     
{
    output = output + rows.ToString() + "\n";
}

However, I think I'm missing something because this isn't working. Can someone point me in the right direction?

但是,我想我错过了一些东西,因为这不起作用。有人可以指出我正确的方向吗?

采纳答案by Khan

You need to specify which column of the datarow you want to pull data from.

您需要指定要从中提取数据的数据行的哪一列。

Try the following:

请尝试以下操作:

        StringBuilder output = new StringBuilder();
        foreach (DataRow rows in results.Tables[0].Rows)
        {
            foreach (DataColumn col in results.Tables[0].Columns)
            {
                output.AppendFormat("{0} ", rows[col]);
            }

            output.AppendLine();
        }

回答by Andrei G

Your rowsobject holds an Itemattribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()on the row. You should access each column from the row separately, use a foror a foreachto walk the array of columns.

您的rows对象拥有一个Item属性,您可以在其中找到每个列的值。当您.ToString()在行上执行 a 时,您不能指望列连接起来。您应该分别访问行中的每一列,使用 afor或 aforeach来遍历列数组。

Here, take a look at the class:

在这里,看看这个类:

http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx

http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx

回答by Matthew

You can get a columns value by doing this

您可以通过执行此操作获取列值

 rows["ColumnName"]

You will also have to cast to the appropriate type.

您还必须转换为适当的类型。

 output += (string)rows["ColumnName"]

回答by SPFiredrake

I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:

我自己做了很多。如果您只需要所有行值的逗号分隔列表,您可以这样做:

StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)     
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.

StringBuilder 是首选方法,因为对于大量数据,字符串连接的速度要慢得多。