使用 StringTemplate 输出数据表
我正在尝试实现一种方法,该方法将接受带有 StringTemplate
的 DataTable
并返回数据的字符串表示形式。
示例代码:
// Here can be any table with any number of columns.
var table = new DataTable();
table.Columns.Add("StrCol", typeof(string));
table.Columns.Add("IntCol", typeof(int));
table.Rows.Add(new object[] { "Row1String", 1 });
table.Rows.Add(new object[] { "Row2String", 2 });
var data = from dataRow in table.AsEnumerable()
select dataRow;
var st = new StringTemplate("$items:{$it.StrCol$ $it.IntCol$}$");
st.SetAttribute("items", data);
Console.Write(st.ToString());
结果:
Class DataRow has no such attribute: StrCol in template context [anonymous anonymous]
Class DataRow has no such attribute: IntCol in template context [anonymous anonymous]
Class DataRow has no such attribute: StrCol in template context [anonymous anonymous]
Class DataRow has no such attribute: IntCol in template context [anonymous anonymous]
UPD:
我必须使用StringTemplate
的Antlr3.StringTemplate.dll版本3.1.0 。我决定尝试另一个版本并下载了 Antlr3.StringTemplate.dll 版本 3.3.0。一切正常。那么,有没有办法使用旧库在 DataTable
上应用模板?
I'm trying to implement a method that will accept DataTable
with StringTemplate
and return string representation of data.
I found how to do this here and here, but it doesn't work for me.
Example code:
// Here can be any table with any number of columns.
var table = new DataTable();
table.Columns.Add("StrCol", typeof(string));
table.Columns.Add("IntCol", typeof(int));
table.Rows.Add(new object[] { "Row1String", 1 });
table.Rows.Add(new object[] { "Row2String", 2 });
var data = from dataRow in table.AsEnumerable()
select dataRow;
var st = new StringTemplate("$items:{$it.StrCol$ $it.IntCol$}$");
st.SetAttribute("items", data);
Console.Write(st.ToString());
Result:
Class DataRow has no such attribute: StrCol in template context [anonymous anonymous]
Class DataRow has no such attribute: IntCol in template context [anonymous anonymous]
Class DataRow has no such attribute: StrCol in template context [anonymous anonymous]
Class DataRow has no such attribute: IntCol in template context [anonymous anonymous]
UPD:
I have to use Antlr3.StringTemplate.dll version 3.1.0 of StringTemplate
. I decided to try on another version and downloaded Antlr3.StringTemplate.dll version 3.3.0. Everything works fine. So, is there any way to apply template on DataTable
using old library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
DataTable
上使用字符串模板的可能解决方法是将行转换为字典集合,因此可以通过列名称访问行单元格:使用较新版本的
StringTemplate
与 DataTable 一起使用的库:The possible workaround to use string templates on
DataTable
is to convert rows to collection of dictionaries, so it will be possible to access rows cells by column names:With newer version of
StringTemplate
library that works withDataTable
:要么塑造你的数据行:
要么调整你的StringTemplate(不确定这是否有效)
either shape your datarow:
or adapt your StringTemplate (not sure if that works though)