首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用DataTable输出StringTemplate

使用DataTable输出StringTemplate
EN

Stack Overflow用户
提问于 2012-01-03 14:26:54
回答 2查看 939关注 0票数 3

我正在尝试实现一个方法,该方法将接受带有DataTableStringTemplate并返回数据的字符串表示形式。

我找到了如何做这个这里这里,但它对我不起作用。

示例代码:

代码语言:javascript
复制
// 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());

结果:

代码语言:javascript
复制
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:

我必须使用Antlr3.StringTemplate.dll版本3.1.0 of StringTemplate。我决定尝试另一个版本,并下载了Antlr3.StringTemplate.dll版本3.3.0。一切都很好。那么,有什么方法可以使用旧库在DataTable上应用模板呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-04 12:07:03

DataTable上使用字符串模板的可能解决方法是将行转换为字典的集合,因此可以通过列名访问行单元格:

代码语言:javascript
复制
var columns = table.Columns.Cast<DataColumn>().Select(col => col.ColumnName);
var data = from DataRow row in table.Rows
           select columns.ToDictionary(col => col, col => row[col]);

var st = new StringTemplate("$items:{$it.StrCol$ $it.IntCol$\n}$");
st.SetAttribute("items", data);

使用新版本的StringTemplate库,该库与DataTable一起工作

代码语言:javascript
复制
var st = new StringTemplate("$items:{$it.StrCol$ $it.IntCol$\n}$");
st.SetAttribute("items", table.Rows);
票数 1
EN

Stack Overflow用户

发布于 2012-01-03 14:36:12

要么塑造您的数据方式:

代码语言:javascript
复制
select new { StrCol = dataRow["StrCol"], IntCol = dataRow["IntCol"] }

或者调整您的StringTemplate (但不确定这是否有效)

代码语言:javascript
复制
var st = new StringTemplate("$items:{$it[0]$ $it[1]}$");   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8713741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档