My code can generate HTML table strings well, but it depends on JSON.NET.
I'm converting IEnumerable
to an HTML table string using Json.NET but I think I shouldn't.
void Main()
{
var datas = new[] { new {Name="Test"} };
var array = datas.ToArray().ToHtmlTable(); //Run Success
var set = datas.ToHashSet().ToHtmlTable();//Run Succes
var list = datas.ToList().ToHtmlTable(); //Run Succes
var enums = datas.AsEnumerable().ToHtmlTable(); //Run Succes
}
public static class HTMLTableHelper
{
public static string ToHtmlTable(this IEnumerable enums)
{
return ToHtmlTableConverter(enums);
}
public static string ToHtmlTable(this System.Data.DataTable dataTable)
{
return ConvertDataTableToHTML(dataTable);
}
private static string ToHtmlTableConverter(object enums)
{
var jsonStr = JsonConvert.SerializeObject(enums);
var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
var html = ConvertDataTableToHTML(data);
return html;
}
private static string ConvertDataTableToHTML(System.Data.DataTable dt)
{
var html = new StringBuilder("<table>");
//Header
html.Append("<thead><tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<th>" + dt.Columns[i].ColumnName + "</th>");
html.Append("</tr></thead>");
//Body
html.Append("<tbody>");
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
return html.ToString();
}
}
I think it is bad because SerializeObject
to string could be DeserializeObject
to DataTable
is a waste of efficiency.
var jsonStr = JsonConvert.SerializeObject(enums);
var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
I want to remove dependencies on JSON.NET because it can reduce the size of the library.
Do you think I should replace them with something else if there is a better way?
JsonNet
andDataTable
s :-| Could you reframe your question please? Currently this is very confusing. \$\endgroup\$DeserializeObject
is implemented. \$\endgroup\$