3

DataTableデータの文字列表現を受け入れてStringTemplate返すメソッドを実装しようとしています。

これを行う方法はこちらこちらで見つかりましたが、うまくいきません。

コード例:

// 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]

更新:

Antlr3.StringTemplate.dllバージョン3.1.0を使用する必要がありStringTemplateます。別のバージョンを試すことにし、 Antlr3.StringTemplate.dllバージョン3.3.0をダウンロードしました。すべて正常に動作します。DataTableでは、古いライブラリを使用してテンプレートを適用する方法はありますか?

4

2 に答える 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);

StringTemplateで動作するライブラリの新しいバージョンではDataTable

var st = new StringTemplate("$items:{$it.StrCol$ $it.IntCol$\n}$");
st.SetAttribute("items", table.Rows);
于 2012-01-04T12:07:03.390 に答える
0

あなたのデータ行を形作るか:

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

または StringTemplate を調整します(ただし、それが機能するかどうかはわかりません)

var st = new StringTemplate("$items:{$it[0]$ $it[1]}$");   
于 2012-01-03T14:36:12.367 に答える