0

这是参考此答案中提供的代码:@Tim-Schmelter在此处输入链接描述。

代码是按特定列对 DataTable 进行分组,并向列(数据透视)添加计数:

   public DataTable GroupBy(string i_sGroupByColumn, string i_sAggregateColumn, DataTable i_dSourceTable)
    {

        DataView dv = new DataView(i_dSourceTable);

        //getting distinct values for group column
        DataTable dtGroup = dv.ToTable(true, new string[] { i_sGroupByColumn });

        //adding column for the row count
        dtGroup.Columns.Add("Count", typeof(int));

        //looping thru distinct values for the group, counting
        foreach (DataRow dr in dtGroup.Rows)
        {
            dr["Count"] = i_dSourceTable.Compute("Count(" + i_sAggregateColumn + ")", i_sGroupByColumn + " = '" + dr[i_sGroupByColumn] + "'");
        }

        //returning grouped/counted result
        return dtGroup;
    }

但是,我的数据表有一列(我无法更改),字段名称中有一个空格,即:“解决方案 ID”

当我将它传递到上面的代码中时,使用这个:

DataTable Solutions = GroupBy("Solution ID", "Solution ID", tbQ);

...我收到错误:语法错误:“ID”运算符后缺少操作数。

我试过用[]封装,将空格修改为+,但它不起作用。

是否可以修改上面的代码,以接受其中有空格的列?

谢谢你,马克

4

1 回答 1

1

我试过用[]封装,将空格修改为+,但它不起作用。

好吧,将空间更改为+肯定行不通,但应该封装在括号中。尝试

if(!i_sAggregateColumn.StartsWith("["))
    i_sAggregateColumn = "[" + i_sAggregateColumn + "]";

if(!i_sGroupByColumn.StartsWith("["))
    i_sGroupByColumn = "[" + i_sGroupByColumn + "]";

Note that if your column name already contains brackets you'll have to try something else.

于 2013-01-24T14:04:11.590 回答