我的C#DataTable
格式如下
Name Value1 Value2 Value3
A 5 5 0
B 6 3 1
C 4 9 9
字符串中的预期格式应为
string sDataTableOutput = "A,B,C|Value1,5,6,4|Value2,5,3,9|Value3,0,1,9";
我希望列标题包含数据(第一列除外)
我努力写下面的代码,但无法完成
DataTable dtGraphOutput[0] = //Get DataTable Data ;
foreach (DataColumn dcOutput in dtGraphOutput[0].Columns)
{
foreach (DataRow drOutput in dtGraphOutput[0].Rows)
{
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : ",") + dcOutput.ColumnName + Convert.ToString(drOutput[dcOutput]);
}
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : "|");
}
它给我输出
NameA,NameB,NameC|,Value15,Value16,Value14|,Value25,Value23,Value29|,Value30,Value31,Value39|
答案 0 :(得分:1)
这是LINQ并为您提供所需的结果:
var rows = dt.AsEnumerable();
var firstCol = string.Join(",", rows.Select(r => r.Field<string>(0)));
var otherColumns = dt.Columns.Cast<DataColumn>().Skip(1)
.Select(dc => string.Format("{0},{1}",
dc.ColumnName,
string.Join(",", rows.Select(r => r.Field<int>(dc)))));
string sDataTableOutput = string.Format("{0}|{1}",
firstCol,
string.Join("|", otherColumns));
结果:A,B,C|Value1,5,6,4|Value2,5,3,9|Value3,0,1,9
答案 1 :(得分:1)
string sDataTableOutput = string.Join("|",
dtGraphOutput[0].Columns
.OfType<DataColumn>()
.Select((c,i) =>
string.Join(",",
dtGraphOutput[0].Rows
.OfType<DataRow>()
.Select((r,j)=>
(j == 0 && i != 0 ? c.ColumnName + "," : "") + r[c.ColumnName])
.ToArray())).ToArray());
.
答案 2 :(得分:0)
试试这个:
DataTable dtGraphOutput[0] = //Get DataTable Data ;
foreach (DataColumn dcOutput in dtGraphOutput[0].Columns)
{
sTicketTypeCount +=dcOutput.ColumnName
foreach (DataRow drOutput in dtGraphOutput[0].Rows)
{
sTicketTypeCount += ","+ dcOutput.ColumnName + Convert.ToString(drOutput[dcOutput]);
}
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : "|");
}
如果您对上一个“|”有疑问您可以使用简单的if
删除它