简体   繁体   English

如何将DataTable列的整个内容转换为C#中的分隔字符串?

[英]how to convert the entire content of a DataTable column to a delimited string in C#?

I am retrieving data from an MSSQL server using the SqlDataAdapter and DataSet. 我正在使用SqlDataAdapter和DataSet从MSSQL服务器检索数据。 From that DataSet I am creating a DataTable. 从那个DataSet我创建了一个DataTable。 My goal is to convert each column of the table into a string where the elements are comma delimited. 我的目标是将表的每一列转换为字符串,其中元素以逗号分隔。 I figured that I would try the string conversion first before making the delimiter work. 我想我会在分隔符工作之前先尝试字符串转换。

The code runs in the code-behind of an ASP.Net page. 代码在ASP.Net页面的代码隐藏中运行。 The ultimate goal is to pass the string to a jscript variable, it's a "functional requirement" that I create a delimited string from the columns and that it has to end up as a jscript variable. 最终的目标是将字符串传递给jscript变量,这是一个“功能需求”,我从列创建一个分隔的字符串,并且它必须最终作为jscript变量。

Here's what I have thus far: 这是我到目前为止所拥有的:

    DataSet myDataSet = new DataSet();
    mySqlDataAdapter.Fill(myDataSet);
    DataTable temperature = myDataSet.Tables["Table"];

    // LOOP1
    foreach (DataRow row in temperature.Rows)
    // this loop works fine and outputs all elements
    // of the table to the web page, this is just to
    // test things out
    {
        foreach (DataColumn col in temperature.Columns)
        {
            Response.Write(row[col] + " ### ");
        }
        Response.Write("<br>");
    }

    // LOOP2
    foreach (DataColumn column in temperature.Columns)
    // this loop was meant to take all elements for each
    // column and create a string, then output that string
    {
        Response.Write(column.ToString() + "<br>");
    }

In LOOP1 things work fine. 在LOOP1中,一切正常。 My data has 4 columns, all are appropriately rendered with one record per row on the web page. 我的数据有4列,所有列都适当地呈现在网页上每行一条记录。

I saw the code for LOOP2 at http://msdn.microsoft.com/en-us/library/system.data.datacolumn.tostring.aspx which seems to do exactly what I need except it does not actually do what I want. 我在http://msdn.microsoft.com/en-us/library/system.data.datacolumn.tostring.aspx上看到了LOOP2的代码,这似乎完全符合我的需要,除了它实际上并没有我想做的事情。

The only thing LOOP2 does is write 4 lines to the web page. LOOP2唯一能做的就是在网页上写4行。 Each line has the header of the respective table column but none of the additional data. 每行都有相应表列的标题,但没有其他数据。 Clearly there's either a logic flaw on my part or I misunderstand how DataColumn and .toString for it works. 显然,我有一个逻辑缺陷,或者我误解了DataColumn和.toString是如何工作的。 Please help me out on this one. 请帮我解决这个问题。 Thanks in advance. 提前致谢。

EDIT: Here's an SQL query result example, this is what the Table looks like: Table quesry result @ ImageShack 编辑:这是一个SQL查询结果示例,这就是表的样子: 表格问题结果@ ImageShack

What I want to end up are four strings, here's an example for the string that would be created from the second column: "-6.7, -7, -7.2, -7.3, -7.3". 我想要结束的是四个字符串,这是从第二列创建的字符串的示例:“ - 6.7,-7,-7.2,-7.3,-7.3”。

This code will concatenate values from cells under each column with ", " : 此代码将使用", "将每列下的单元格的值连接起来:

foreach (var column in temperature.Columns)
{
    DataColumn dc = column as DataColumn;
    string s = string.Join(", ", temperature.Rows.OfType<DataRow>()
                                                 .Select(r => r[dc]));
    // do whatever you need with s now
}

For example, for DataTable defined as: 例如,对于DataTable定义为:

DataTable table = new DataTable();
table.Columns.Add(new DataColumn("Column #1"));
table.Columns.Add(new DataColumn("Column #2"));
table.Rows.Add(1, 2);
table.Rows.Add(11, 22);
table.Rows.Add(111, 222);

... it will produce "1, 11, 111" and "2, 22, 222" strings. ......它会产生"1, 11, 111""2, 22, 222"字符串。


Edit: I saw you chose to declare column as var as opposed to DataColumn, is that a matter of personal preference/style or is there an issue with coding? 编辑: 我看到你选择将列声明为var而不是DataColumn,这是个人偏好/风格的问题还是编码存在问题?

Consider following scenario (on the same data table example as above): 考虑以下场景(在与上面相同的数据表示例中):

// we decide we'll use results later, storing them temporarily here
List<IEnumerable<string>> columnsValues = new List<IEnumerable<string>>();
foreach (DataColumn column in temperature.Columns)
{
    var values = temperature.Rows.OfType<DataRow>()
                                 .Select(r => r[column].ToString())
    columnsValues.Add(values);
}

We assume we now got list of list of column values. 我们假设我们现在得到了列值列表的列表。 So, when we print them, like this: 所以,当我们打印它们时,像这样:

foreach (var lisOfValues in columnsValues)
{
    foreach (var value in listOfValues)
    {
        Debug.Write(value + " ");
    }

    Debug.WriteLine("");
}

We expect to see 1 11 111 followed by 2 22 222 . 我们预计会看到1 11 111然后是2 22 222 Right? 对?

Wrong . 错了

This code will output 2 22 222 twice. 此代码将两次输出2 22 222 Why? 为什么? Our .Select(r => r[column].ToString()) captures column variable - not its value, but variable itself - and since we don't use it immediately, once we're out of loop all we know is last value of column . 我们的.Select(r => r[column].ToString()) 捕获 column变量 - 不是它的值,而是变量本身 - 因为我们不立即使用它,一旦我们离开循环,我们所知道的是最后一个 column值。

To learn more about this concept search for closures and captured variables - for example, in posts like this . 要了解有关此概念的更多信息,请搜索闭包捕获的变量 - 例如,在此类帖子中。

Summary : 摘要

In this very case you can go with DataColumn in foreach statement. 在这种情况下,您可以在foreach语句中使用DataColumn It doesn't matter here because we're enumerating through our .Select(r => r[dc]) either way inside the loop (precisely, string.Join does that for us), producing results before we get to next iteration - whatever we capture, is used immediately. 这没关系,因为我们在循环内部通过我们的.Select(r => r[dc])进行枚举(确切地说, string.Join为我们做了这一点),在我们进入下一次迭代之前产生结果 -无论我们捕获什么,都会立即使用。

The link you have posted clearly states 您发布的链接清楚地说明了

The Expression value, if the property is set; 如果设置了属性,则为Expression值; otherwise, the ColumnName property. 否则,ColumnName属性。

and that is what is happening. 这就是正在发生的事情。 You get column names. 你得到列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM