如何使用DataTable.Select()访问具有特殊字符的列?

时间:2012-04-10 00:22:13

标签: c# datatable datacolumn

我有一个DataTable列,例如# of Students,并希望按降序排序。这是我的代码:

...
dt.Columns.Add(new DataColumn("# of Students", typeof(string)));

// do some stuff... add records etc.

// A runtime error occurs here: "Cannot find column '# of Students'"
var rows = dt.Select("","'# of Students' desc");

// this is just fine.
rows = dt.Select("","# of Students");

如果名称中包含特殊字符,我该如何访问此列?

2 个答案:

答案 0 :(得分:3)

您可以使用[]或``语法。以下两个片段都是正确的:

var rows = dt.Select("","`# of Students` desc");

var rows = dt.Select("","[# of Students] desc");

答案 1 :(得分:2)

您应该使用[]括号,如下所示:

var rows = dt.Select("","[# of Students] desc");