使用StringTemplate输出DataTable

3
我正在尝试实现一个方法,它将接受带有StringTemplate的DataTable并返回数据的字符串表示形式。
我在这里找到了如何做到这一点herehere,但对我来说不起作用。
示例代码:
// 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]

更新:

我必须使用StringTemplate的版本3.1.0,需要使用Antlr3.StringTemplate.dll。我决定尝试另一个版本并下载了Antlr3.StringTemplate.dll版本3.3.0。一切正常运行。那么,有没有办法在旧的库中应用DataTable上的模板?

2个回答

1

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

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);

随着与 DataTable 兼容的较新版本的 StringTemplate 库:

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

0

将您的数据行进行塑形:

select new { StrCol = dataRow["StrCol"], IntCol = dataRow["IntCol"] }

或者适应您的StringTemplate(不确定是否有效)

var st = new StringTemplate("$items:{$it[0]$ $it[1]}$");   

1
问题在于我不能这样硬编码匿名类型,因为我的代码应该适用于任何DataTable - kyrylomyr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接