2012-01-03 12 views
3

DataTableを受け入れ、StringTemplateを受け取り、データの文字列表現を返すメソッドを実装しようとしています。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] 

UPD:私はStringTemplate3.1.0Antlr3.StringTemplate.dllバージョンを使用する必要が

。私は別のバージョンを試してみることにしました。Antlr3.StringTemplate.dllバージョン3.3.0をダウンロードしました。すべてうまく動作します。では、古いライブラリを使用してDataTableにテンプレートを適用する方法はありますか? (それはしかし動作するかどうかわからない)

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

答えて

1

DataTableに文字列テンプレートを使用することが可能な回避策は、コレクションに行を変換することです

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

たりStringTemplateを適応させる:

0

どちらかあなたのDataRowを形作ります行のセルに列名でアクセスすることができます。

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ライブラリの新しいバージョンでは

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

私のコードは**どの** 'DataTable'で動作するはずですので、私は匿名型をそのようにハードコーディングすることはできません問題。 –

関連する問題